blob: a981ffdf6e72179b008d2f3d30aa3de2e3c2e66a [file] [log] [blame]
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001//===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
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"
29
30using namespace clang;
31using llvm::utostr;
32
33namespace {
34 class RewriteModernObjC : public ASTConsumer {
35 protected:
36
37 enum {
38 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
39 block, ... */
40 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
41 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
42 __block variable */
43 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
44 helpers */
45 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
46 support routines */
47 BLOCK_BYREF_CURRENT_MAX = 256
48 };
49
50 enum {
51 BLOCK_NEEDS_FREE = (1 << 24),
52 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
53 BLOCK_HAS_CXX_OBJ = (1 << 26),
54 BLOCK_IS_GC = (1 << 27),
55 BLOCK_IS_GLOBAL = (1 << 28),
56 BLOCK_HAS_DESCRIPTOR = (1 << 29)
57 };
58 static const int OBJC_ABI_VERSION = 7;
59
60 Rewriter Rewrite;
61 DiagnosticsEngine &Diags;
62 const LangOptions &LangOpts;
63 ASTContext *Context;
64 SourceManager *SM;
65 TranslationUnitDecl *TUDecl;
66 FileID MainFileID;
67 const char *MainFileStart, *MainFileEnd;
68 Stmt *CurrentBody;
69 ParentMap *PropParentMap; // created lazily.
70 std::string InFileName;
71 raw_ostream* OutFile;
72 std::string Preamble;
73
74 TypeDecl *ProtocolTypeDecl;
75 VarDecl *GlobalVarDecl;
76 unsigned RewriteFailedDiag;
77 // ObjC string constant support.
78 unsigned NumObjCStringLiterals;
79 VarDecl *ConstantStringClassReference;
80 RecordDecl *NSStringRecord;
81
82 // ObjC foreach break/continue generation support.
83 int BcLabelCount;
84
85 unsigned TryFinallyContainsReturnDiag;
86 // Needed for super.
87 ObjCMethodDecl *CurMethodDef;
88 RecordDecl *SuperStructDecl;
89 RecordDecl *ConstantStringDecl;
90
91 FunctionDecl *MsgSendFunctionDecl;
92 FunctionDecl *MsgSendSuperFunctionDecl;
93 FunctionDecl *MsgSendStretFunctionDecl;
94 FunctionDecl *MsgSendSuperStretFunctionDecl;
95 FunctionDecl *MsgSendFpretFunctionDecl;
96 FunctionDecl *GetClassFunctionDecl;
97 FunctionDecl *GetMetaClassFunctionDecl;
98 FunctionDecl *GetSuperClassFunctionDecl;
99 FunctionDecl *SelGetUidFunctionDecl;
100 FunctionDecl *CFStringFunctionDecl;
101 FunctionDecl *SuperContructorFunctionDecl;
102 FunctionDecl *CurFunctionDef;
103 FunctionDecl *CurFunctionDeclToDeclareForBlock;
104
105 /* Misc. containers needed for meta-data rewrite. */
106 SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
107 SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
108 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
109 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
110 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
111 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
112 SmallVector<Stmt *, 32> Stmts;
113 SmallVector<int, 8> ObjCBcLabelNo;
114 // Remember all the @protocol(<expr>) expressions.
115 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
116
117 llvm::DenseSet<uint64_t> CopyDestroyCache;
118
119 // Block expressions.
120 SmallVector<BlockExpr *, 32> Blocks;
121 SmallVector<int, 32> InnerDeclRefsCount;
122 SmallVector<BlockDeclRefExpr *, 32> InnerDeclRefs;
123
124 SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
125
126 // Block related declarations.
127 SmallVector<ValueDecl *, 8> BlockByCopyDecls;
128 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
129 SmallVector<ValueDecl *, 8> BlockByRefDecls;
130 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
131 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
132 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
133 llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
134
135 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
136
137 // This maps an original source AST to it's rewritten form. This allows
138 // us to avoid rewriting the same node twice (which is very uncommon).
139 // This is needed to support some of the exotic property rewriting.
140 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
141
142 // Needed for header files being rewritten
143 bool IsHeader;
144 bool SilenceRewriteMacroWarning;
145 bool objc_impl_method;
146
147 bool DisableReplaceStmt;
148 class DisableReplaceStmtScope {
149 RewriteModernObjC &R;
150 bool SavedValue;
151
152 public:
153 DisableReplaceStmtScope(RewriteModernObjC &R)
154 : R(R), SavedValue(R.DisableReplaceStmt) {
155 R.DisableReplaceStmt = true;
156 }
157 ~DisableReplaceStmtScope() {
158 R.DisableReplaceStmt = SavedValue;
159 }
160 };
161 void InitializeCommon(ASTContext &context);
162
163 public:
164
165 // Top Level Driver code.
166 virtual bool HandleTopLevelDecl(DeclGroupRef D) {
167 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
168 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*I)) {
169 if (!Class->isThisDeclarationADefinition()) {
170 RewriteForwardClassDecl(D);
171 break;
172 }
173 }
174
175 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*I)) {
176 if (!Proto->isThisDeclarationADefinition()) {
177 RewriteForwardProtocolDecl(D);
178 break;
179 }
180 }
181
182 HandleTopLevelSingleDecl(*I);
183 }
184 return true;
185 }
186 void HandleTopLevelSingleDecl(Decl *D);
187 void HandleDeclInMainFile(Decl *D);
188 RewriteModernObjC(std::string inFile, raw_ostream *OS,
189 DiagnosticsEngine &D, const LangOptions &LOpts,
190 bool silenceMacroWarn);
191
192 ~RewriteModernObjC() {}
193
194 virtual void HandleTranslationUnit(ASTContext &C);
195
196 void ReplaceStmt(Stmt *Old, Stmt *New) {
197 Stmt *ReplacingStmt = ReplacedNodes[Old];
198
199 if (ReplacingStmt)
200 return; // We can't rewrite the same node twice.
201
202 if (DisableReplaceStmt)
203 return;
204
205 // If replacement succeeded or warning disabled return with no warning.
206 if (!Rewrite.ReplaceStmt(Old, New)) {
207 ReplacedNodes[Old] = New;
208 return;
209 }
210 if (SilenceRewriteMacroWarning)
211 return;
212 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
213 << Old->getSourceRange();
214 }
215
216 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
217 if (DisableReplaceStmt)
218 return;
219
220 // Measure the old text.
221 int Size = Rewrite.getRangeSize(SrcRange);
222 if (Size == -1) {
223 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
224 << Old->getSourceRange();
225 return;
226 }
227 // Get the new text.
228 std::string SStr;
229 llvm::raw_string_ostream S(SStr);
230 New->printPretty(S, *Context, 0, PrintingPolicy(LangOpts));
231 const std::string &Str = S.str();
232
233 // If replacement succeeded or warning disabled return with no warning.
234 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
235 ReplacedNodes[Old] = New;
236 return;
237 }
238 if (SilenceRewriteMacroWarning)
239 return;
240 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
241 << Old->getSourceRange();
242 }
243
244 void InsertText(SourceLocation Loc, StringRef Str,
245 bool InsertAfter = true) {
246 // If insertion succeeded or warning disabled return with no warning.
247 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
248 SilenceRewriteMacroWarning)
249 return;
250
251 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
252 }
253
254 void ReplaceText(SourceLocation Start, unsigned OrigLength,
255 StringRef Str) {
256 // If removal succeeded or warning disabled return with no warning.
257 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
258 SilenceRewriteMacroWarning)
259 return;
260
261 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
262 }
263
264 // Syntactic Rewriting.
265 void RewriteRecordBody(RecordDecl *RD);
266 void RewriteInclude();
267 void RewriteForwardClassDecl(DeclGroupRef D);
268 void RewriteForwardClassDecl(const llvm::SmallVector<Decl*, 8> &DG);
269 void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
270 const std::string &typedefString);
271 void RewriteImplementations();
272 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
273 ObjCImplementationDecl *IMD,
274 ObjCCategoryImplDecl *CID);
275 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
276 void RewriteImplementationDecl(Decl *Dcl);
277 void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
278 ObjCMethodDecl *MDecl, std::string &ResultStr);
279 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
280 const FunctionType *&FPRetType);
281 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
282 ValueDecl *VD, bool def=false);
283 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
284 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
285 void RewriteForwardProtocolDecl(DeclGroupRef D);
286 void RewriteForwardProtocolDecl(const llvm::SmallVector<Decl*, 8> &DG);
287 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
288 void RewriteProperty(ObjCPropertyDecl *prop);
289 void RewriteFunctionDecl(FunctionDecl *FD);
290 void RewriteBlockPointerType(std::string& Str, QualType Type);
291 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
292 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
293 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
294 void RewriteTypeOfDecl(VarDecl *VD);
295 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
296
297 // Expression Rewriting.
298 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
299 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
300 Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
301 Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
302 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
303 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
304 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
305 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
306 void RewriteTryReturnStmts(Stmt *S);
307 void RewriteSyncReturnStmts(Stmt *S, std::string buf);
308 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
309 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
310 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
311 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
312 SourceLocation OrigEnd);
313 Stmt *RewriteBreakStmt(BreakStmt *S);
314 Stmt *RewriteContinueStmt(ContinueStmt *S);
315 void RewriteCastExpr(CStyleCastExpr *CE);
316
317 // Block rewriting.
318 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
319
320 // Block specific rewrite rules.
321 void RewriteBlockPointerDecl(NamedDecl *VD);
322 void RewriteByRefVar(VarDecl *VD);
323 Stmt *RewriteBlockDeclRefExpr(Expr *VD);
324 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
325 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
326
327 void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
328 std::string &Result);
329
330 virtual void Initialize(ASTContext &context);
331
332 // Misc. AST transformation routines. Somtimes they end up calling
333 // rewriting routines on the new ASTs.
334 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
335 Expr **args, unsigned nargs,
336 SourceLocation StartLoc=SourceLocation(),
337 SourceLocation EndLoc=SourceLocation());
338
339 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
340 SourceLocation StartLoc=SourceLocation(),
341 SourceLocation EndLoc=SourceLocation());
342
343 void SynthCountByEnumWithState(std::string &buf);
344 void SynthMsgSendFunctionDecl();
345 void SynthMsgSendSuperFunctionDecl();
346 void SynthMsgSendStretFunctionDecl();
347 void SynthMsgSendFpretFunctionDecl();
348 void SynthMsgSendSuperStretFunctionDecl();
349 void SynthGetClassFunctionDecl();
350 void SynthGetMetaClassFunctionDecl();
351 void SynthGetSuperClassFunctionDecl();
352 void SynthSelGetUidFunctionDecl();
353 void SynthSuperContructorFunctionDecl();
354
355 // Rewriting metadata
356 template<typename MethodIterator>
357 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
358 MethodIterator MethodEnd,
359 bool IsInstanceMethod,
360 StringRef prefix,
361 StringRef ClassName,
362 std::string &Result);
Fariborz Jahanianda9624a2012-02-08 19:53:58 +0000363 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
364 std::string &Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000365 virtual void RewriteObjCProtocolListMetaData(
366 const ObjCList<ObjCProtocolDecl> &Prots,
367 StringRef prefix, StringRef ClassName, std::string &Result);
368 virtual void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
369 std::string &Result);
370 virtual void RewriteMetaDataIntoBuffer(std::string &Result);
371 virtual void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
372 std::string &Result);
373
374 // Rewriting ivar
375 virtual void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
376 std::string &Result);
377 virtual Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
378
379
380 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
381 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
382 StringRef funcName, std::string Tag);
383 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
384 StringRef funcName, std::string Tag);
385 std::string SynthesizeBlockImpl(BlockExpr *CE,
386 std::string Tag, std::string Desc);
387 std::string SynthesizeBlockDescriptor(std::string DescTag,
388 std::string ImplTag,
389 int i, StringRef funcName,
390 unsigned hasCopy);
391 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
392 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
393 StringRef FunName);
394 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
395 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
396 const SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs);
397
398 // Misc. helper routines.
399 QualType getProtocolType();
400 void WarnAboutReturnGotoStmts(Stmt *S);
401 void HasReturnStmts(Stmt *S, bool &hasReturns);
402 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
403 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
404 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
405
406 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
407 void CollectBlockDeclRefInfo(BlockExpr *Exp);
408 void GetBlockDeclRefExprs(Stmt *S);
409 void GetInnerBlockDeclRefExprs(Stmt *S,
410 SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
411 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
412
413 // We avoid calling Type::isBlockPointerType(), since it operates on the
414 // canonical type. We only care if the top-level type is a closure pointer.
415 bool isTopLevelBlockPointerType(QualType T) {
416 return isa<BlockPointerType>(T);
417 }
418
419 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
420 /// to a function pointer type and upon success, returns true; false
421 /// otherwise.
422 bool convertBlockPointerToFunctionPointer(QualType &T) {
423 if (isTopLevelBlockPointerType(T)) {
424 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
425 T = Context->getPointerType(BPT->getPointeeType());
426 return true;
427 }
428 return false;
429 }
430
431 bool needToScanForQualifiers(QualType T);
432 QualType getSuperStructType();
433 QualType getConstantStringStructType();
434 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
435 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
436
437 void convertToUnqualifiedObjCType(QualType &T) {
438 if (T->isObjCQualifiedIdType())
439 T = Context->getObjCIdType();
440 else if (T->isObjCQualifiedClassType())
441 T = Context->getObjCClassType();
442 else if (T->isObjCObjectPointerType() &&
443 T->getPointeeType()->isObjCQualifiedInterfaceType()) {
444 if (const ObjCObjectPointerType * OBJPT =
445 T->getAsObjCInterfacePointerType()) {
446 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
447 T = QualType(IFaceT, 0);
448 T = Context->getPointerType(T);
449 }
450 }
451 }
452
453 // FIXME: This predicate seems like it would be useful to add to ASTContext.
454 bool isObjCType(QualType T) {
455 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
456 return false;
457
458 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
459
460 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
461 OCT == Context->getCanonicalType(Context->getObjCClassType()))
462 return true;
463
464 if (const PointerType *PT = OCT->getAs<PointerType>()) {
465 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
466 PT->getPointeeType()->isObjCQualifiedIdType())
467 return true;
468 }
469 return false;
470 }
471 bool PointerTypeTakesAnyBlockArguments(QualType QT);
472 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
473 void GetExtentOfArgList(const char *Name, const char *&LParen,
474 const char *&RParen);
475
476 void QuoteDoublequotes(std::string &From, std::string &To) {
477 for (unsigned i = 0; i < From.length(); i++) {
478 if (From[i] == '"')
479 To += "\\\"";
480 else
481 To += From[i];
482 }
483 }
484
485 QualType getSimpleFunctionType(QualType result,
486 const QualType *args,
487 unsigned numArgs,
488 bool variadic = false) {
489 if (result == Context->getObjCInstanceType())
490 result = Context->getObjCIdType();
491 FunctionProtoType::ExtProtoInfo fpi;
492 fpi.Variadic = variadic;
493 return Context->getFunctionType(result, args, numArgs, fpi);
494 }
495
496 // Helper function: create a CStyleCastExpr with trivial type source info.
497 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
498 CastKind Kind, Expr *E) {
499 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
500 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, 0, TInfo,
501 SourceLocation(), SourceLocation());
502 }
503 };
504
505}
506
507void RewriteModernObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
508 NamedDecl *D) {
509 if (const FunctionProtoType *fproto
510 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
511 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
512 E = fproto->arg_type_end(); I && (I != E); ++I)
513 if (isTopLevelBlockPointerType(*I)) {
514 // All the args are checked/rewritten. Don't call twice!
515 RewriteBlockPointerDecl(D);
516 break;
517 }
518 }
519}
520
521void RewriteModernObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
522 const PointerType *PT = funcType->getAs<PointerType>();
523 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
524 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
525}
526
527static bool IsHeaderFile(const std::string &Filename) {
528 std::string::size_type DotPos = Filename.rfind('.');
529
530 if (DotPos == std::string::npos) {
531 // no file extension
532 return false;
533 }
534
535 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
536 // C header: .h
537 // C++ header: .hh or .H;
538 return Ext == "h" || Ext == "hh" || Ext == "H";
539}
540
541RewriteModernObjC::RewriteModernObjC(std::string inFile, raw_ostream* OS,
542 DiagnosticsEngine &D, const LangOptions &LOpts,
543 bool silenceMacroWarn)
544 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
545 SilenceRewriteMacroWarning(silenceMacroWarn) {
546 IsHeader = IsHeaderFile(inFile);
547 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
548 "rewriting sub-expression within a macro (may not be correct)");
549 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
550 DiagnosticsEngine::Warning,
551 "rewriter doesn't support user-specified control flow semantics "
552 "for @try/@finally (code may not execute properly)");
553}
554
555ASTConsumer *clang::CreateModernObjCRewriter(const std::string& InFile,
556 raw_ostream* OS,
557 DiagnosticsEngine &Diags,
558 const LangOptions &LOpts,
559 bool SilenceRewriteMacroWarning) {
560 return new RewriteModernObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
561}
562
563void RewriteModernObjC::InitializeCommon(ASTContext &context) {
564 Context = &context;
565 SM = &Context->getSourceManager();
566 TUDecl = Context->getTranslationUnitDecl();
567 MsgSendFunctionDecl = 0;
568 MsgSendSuperFunctionDecl = 0;
569 MsgSendStretFunctionDecl = 0;
570 MsgSendSuperStretFunctionDecl = 0;
571 MsgSendFpretFunctionDecl = 0;
572 GetClassFunctionDecl = 0;
573 GetMetaClassFunctionDecl = 0;
574 GetSuperClassFunctionDecl = 0;
575 SelGetUidFunctionDecl = 0;
576 CFStringFunctionDecl = 0;
577 ConstantStringClassReference = 0;
578 NSStringRecord = 0;
579 CurMethodDef = 0;
580 CurFunctionDef = 0;
581 CurFunctionDeclToDeclareForBlock = 0;
582 GlobalVarDecl = 0;
583 SuperStructDecl = 0;
584 ProtocolTypeDecl = 0;
585 ConstantStringDecl = 0;
586 BcLabelCount = 0;
587 SuperContructorFunctionDecl = 0;
588 NumObjCStringLiterals = 0;
589 PropParentMap = 0;
590 CurrentBody = 0;
591 DisableReplaceStmt = false;
592 objc_impl_method = false;
593
594 // Get the ID and start/end of the main file.
595 MainFileID = SM->getMainFileID();
596 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
597 MainFileStart = MainBuf->getBufferStart();
598 MainFileEnd = MainBuf->getBufferEnd();
599
600 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
601}
602
603//===----------------------------------------------------------------------===//
604// Top Level Driver Code
605//===----------------------------------------------------------------------===//
606
607void RewriteModernObjC::HandleTopLevelSingleDecl(Decl *D) {
608 if (Diags.hasErrorOccurred())
609 return;
610
611 // Two cases: either the decl could be in the main file, or it could be in a
612 // #included file. If the former, rewrite it now. If the later, check to see
613 // if we rewrote the #include/#import.
614 SourceLocation Loc = D->getLocation();
615 Loc = SM->getExpansionLoc(Loc);
616
617 // If this is for a builtin, ignore it.
618 if (Loc.isInvalid()) return;
619
620 // Look for built-in declarations that we need to refer during the rewrite.
621 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
622 RewriteFunctionDecl(FD);
623 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
624 // declared in <Foundation/NSString.h>
625 if (FVD->getName() == "_NSConstantStringClassReference") {
626 ConstantStringClassReference = FVD;
627 return;
628 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000629 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
630 RewriteCategoryDecl(CD);
631 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
632 if (PD->isThisDeclarationADefinition())
633 RewriteProtocolDecl(PD);
634 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
635 // Recurse into linkage specifications
636 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
637 DIEnd = LSD->decls_end();
638 DI != DIEnd; ) {
639 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
640 if (!IFace->isThisDeclarationADefinition()) {
641 SmallVector<Decl *, 8> DG;
642 SourceLocation StartLoc = IFace->getLocStart();
643 do {
644 if (isa<ObjCInterfaceDecl>(*DI) &&
645 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
646 StartLoc == (*DI)->getLocStart())
647 DG.push_back(*DI);
648 else
649 break;
650
651 ++DI;
652 } while (DI != DIEnd);
653 RewriteForwardClassDecl(DG);
654 continue;
655 }
656 }
657
658 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
659 if (!Proto->isThisDeclarationADefinition()) {
660 SmallVector<Decl *, 8> DG;
661 SourceLocation StartLoc = Proto->getLocStart();
662 do {
663 if (isa<ObjCProtocolDecl>(*DI) &&
664 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
665 StartLoc == (*DI)->getLocStart())
666 DG.push_back(*DI);
667 else
668 break;
669
670 ++DI;
671 } while (DI != DIEnd);
672 RewriteForwardProtocolDecl(DG);
673 continue;
674 }
675 }
676
677 HandleTopLevelSingleDecl(*DI);
678 ++DI;
679 }
680 }
681 // If we have a decl in the main file, see if we should rewrite it.
682 if (SM->isFromMainFile(Loc))
683 return HandleDeclInMainFile(D);
684}
685
686//===----------------------------------------------------------------------===//
687// Syntactic (non-AST) Rewriting Code
688//===----------------------------------------------------------------------===//
689
690void RewriteModernObjC::RewriteInclude() {
691 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
692 StringRef MainBuf = SM->getBufferData(MainFileID);
693 const char *MainBufStart = MainBuf.begin();
694 const char *MainBufEnd = MainBuf.end();
695 size_t ImportLen = strlen("import");
696
697 // Loop over the whole file, looking for includes.
698 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
699 if (*BufPtr == '#') {
700 if (++BufPtr == MainBufEnd)
701 return;
702 while (*BufPtr == ' ' || *BufPtr == '\t')
703 if (++BufPtr == MainBufEnd)
704 return;
705 if (!strncmp(BufPtr, "import", ImportLen)) {
706 // replace import with include
707 SourceLocation ImportLoc =
708 LocStart.getLocWithOffset(BufPtr-MainBufStart);
709 ReplaceText(ImportLoc, ImportLen, "include");
710 BufPtr += ImportLen;
711 }
712 }
713 }
714}
715
716static std::string getIvarAccessString(ObjCIvarDecl *OID) {
717 const ObjCInterfaceDecl *ClassDecl = OID->getContainingInterface();
718 std::string S;
719 S = "((struct ";
720 S += ClassDecl->getIdentifier()->getName();
721 S += "_IMPL *)self)->";
722 S += OID->getName();
723 return S;
724}
725
726void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
727 ObjCImplementationDecl *IMD,
728 ObjCCategoryImplDecl *CID) {
729 static bool objcGetPropertyDefined = false;
730 static bool objcSetPropertyDefined = false;
731 SourceLocation startLoc = PID->getLocStart();
732 InsertText(startLoc, "// ");
733 const char *startBuf = SM->getCharacterData(startLoc);
734 assert((*startBuf == '@') && "bogus @synthesize location");
735 const char *semiBuf = strchr(startBuf, ';');
736 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
737 SourceLocation onePastSemiLoc =
738 startLoc.getLocWithOffset(semiBuf-startBuf+1);
739
740 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
741 return; // FIXME: is this correct?
742
743 // Generate the 'getter' function.
744 ObjCPropertyDecl *PD = PID->getPropertyDecl();
745 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
746
747 if (!OID)
748 return;
749 unsigned Attributes = PD->getPropertyAttributes();
750 if (!PD->getGetterMethodDecl()->isDefined()) {
751 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
752 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
753 ObjCPropertyDecl::OBJC_PR_copy));
754 std::string Getr;
755 if (GenGetProperty && !objcGetPropertyDefined) {
756 objcGetPropertyDefined = true;
757 // FIXME. Is this attribute correct in all cases?
758 Getr = "\nextern \"C\" __declspec(dllimport) "
759 "id objc_getProperty(id, SEL, long, bool);\n";
760 }
761 RewriteObjCMethodDecl(OID->getContainingInterface(),
762 PD->getGetterMethodDecl(), Getr);
763 Getr += "{ ";
764 // Synthesize an explicit cast to gain access to the ivar.
765 // See objc-act.c:objc_synthesize_new_getter() for details.
766 if (GenGetProperty) {
767 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
768 Getr += "typedef ";
769 const FunctionType *FPRetType = 0;
770 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
771 FPRetType);
772 Getr += " _TYPE";
773 if (FPRetType) {
774 Getr += ")"; // close the precedence "scope" for "*".
775
776 // Now, emit the argument types (if any).
777 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
778 Getr += "(";
779 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
780 if (i) Getr += ", ";
781 std::string ParamStr = FT->getArgType(i).getAsString(
782 Context->getPrintingPolicy());
783 Getr += ParamStr;
784 }
785 if (FT->isVariadic()) {
786 if (FT->getNumArgs()) Getr += ", ";
787 Getr += "...";
788 }
789 Getr += ")";
790 } else
791 Getr += "()";
792 }
793 Getr += ";\n";
794 Getr += "return (_TYPE)";
795 Getr += "objc_getProperty(self, _cmd, ";
796 RewriteIvarOffsetComputation(OID, Getr);
797 Getr += ", 1)";
798 }
799 else
800 Getr += "return " + getIvarAccessString(OID);
801 Getr += "; }";
802 InsertText(onePastSemiLoc, Getr);
803 }
804
805 if (PD->isReadOnly() || PD->getSetterMethodDecl()->isDefined())
806 return;
807
808 // Generate the 'setter' function.
809 std::string Setr;
810 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
811 ObjCPropertyDecl::OBJC_PR_copy);
812 if (GenSetProperty && !objcSetPropertyDefined) {
813 objcSetPropertyDefined = true;
814 // FIXME. Is this attribute correct in all cases?
815 Setr = "\nextern \"C\" __declspec(dllimport) "
816 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
817 }
818
819 RewriteObjCMethodDecl(OID->getContainingInterface(),
820 PD->getSetterMethodDecl(), Setr);
821 Setr += "{ ";
822 // Synthesize an explicit cast to initialize the ivar.
823 // See objc-act.c:objc_synthesize_new_setter() for details.
824 if (GenSetProperty) {
825 Setr += "objc_setProperty (self, _cmd, ";
826 RewriteIvarOffsetComputation(OID, Setr);
827 Setr += ", (id)";
828 Setr += PD->getName();
829 Setr += ", ";
830 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
831 Setr += "0, ";
832 else
833 Setr += "1, ";
834 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
835 Setr += "1)";
836 else
837 Setr += "0)";
838 }
839 else {
840 Setr += getIvarAccessString(OID) + " = ";
841 Setr += PD->getName();
842 }
843 Setr += "; }";
844 InsertText(onePastSemiLoc, Setr);
845}
846
847static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
848 std::string &typedefString) {
849 typedefString += "#ifndef _REWRITER_typedef_";
850 typedefString += ForwardDecl->getNameAsString();
851 typedefString += "\n";
852 typedefString += "#define _REWRITER_typedef_";
853 typedefString += ForwardDecl->getNameAsString();
854 typedefString += "\n";
855 typedefString += "typedef struct objc_object ";
856 typedefString += ForwardDecl->getNameAsString();
857 typedefString += ";\n#endif\n";
858}
859
860void RewriteModernObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
861 const std::string &typedefString) {
862 SourceLocation startLoc = ClassDecl->getLocStart();
863 const char *startBuf = SM->getCharacterData(startLoc);
864 const char *semiPtr = strchr(startBuf, ';');
865 // Replace the @class with typedefs corresponding to the classes.
866 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
867}
868
869void RewriteModernObjC::RewriteForwardClassDecl(DeclGroupRef D) {
870 std::string typedefString;
871 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
872 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(*I);
873 if (I == D.begin()) {
874 // Translate to typedef's that forward reference structs with the same name
875 // as the class. As a convenience, we include the original declaration
876 // as a comment.
877 typedefString += "// @class ";
878 typedefString += ForwardDecl->getNameAsString();
879 typedefString += ";\n";
880 }
881 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
882 }
883 DeclGroupRef::iterator I = D.begin();
884 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
885}
886
887void RewriteModernObjC::RewriteForwardClassDecl(
888 const llvm::SmallVector<Decl*, 8> &D) {
889 std::string typedefString;
890 for (unsigned i = 0; i < D.size(); i++) {
891 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
892 if (i == 0) {
893 typedefString += "// @class ";
894 typedefString += ForwardDecl->getNameAsString();
895 typedefString += ";\n";
896 }
897 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
898 }
899 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
900}
901
902void RewriteModernObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
903 // When method is a synthesized one, such as a getter/setter there is
904 // nothing to rewrite.
905 if (Method->isImplicit())
906 return;
907 SourceLocation LocStart = Method->getLocStart();
908 SourceLocation LocEnd = Method->getLocEnd();
909
910 if (SM->getExpansionLineNumber(LocEnd) >
911 SM->getExpansionLineNumber(LocStart)) {
912 InsertText(LocStart, "#if 0\n");
913 ReplaceText(LocEnd, 1, ";\n#endif\n");
914 } else {
915 InsertText(LocStart, "// ");
916 }
917}
918
919void RewriteModernObjC::RewriteProperty(ObjCPropertyDecl *prop) {
920 SourceLocation Loc = prop->getAtLoc();
921
922 ReplaceText(Loc, 0, "// ");
923 // FIXME: handle properties that are declared across multiple lines.
924}
925
926void RewriteModernObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
927 SourceLocation LocStart = CatDecl->getLocStart();
928
929 // FIXME: handle category headers that are declared across multiple lines.
930 ReplaceText(LocStart, 0, "// ");
931
932 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
933 E = CatDecl->prop_end(); I != E; ++I)
934 RewriteProperty(*I);
935
936 for (ObjCCategoryDecl::instmeth_iterator
937 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
938 I != E; ++I)
939 RewriteMethodDeclaration(*I);
940 for (ObjCCategoryDecl::classmeth_iterator
941 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
942 I != E; ++I)
943 RewriteMethodDeclaration(*I);
944
945 // Lastly, comment out the @end.
946 ReplaceText(CatDecl->getAtEndRange().getBegin(),
947 strlen("@end"), "/* @end */");
948}
949
950void RewriteModernObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
951 SourceLocation LocStart = PDecl->getLocStart();
952 assert(PDecl->isThisDeclarationADefinition());
953
954 // FIXME: handle protocol headers that are declared across multiple lines.
955 ReplaceText(LocStart, 0, "// ");
956
957 for (ObjCProtocolDecl::instmeth_iterator
958 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
959 I != E; ++I)
960 RewriteMethodDeclaration(*I);
961 for (ObjCProtocolDecl::classmeth_iterator
962 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
963 I != E; ++I)
964 RewriteMethodDeclaration(*I);
965
966 for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
967 E = PDecl->prop_end(); I != E; ++I)
968 RewriteProperty(*I);
969
970 // Lastly, comment out the @end.
971 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
972 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
973
974 // Must comment out @optional/@required
975 const char *startBuf = SM->getCharacterData(LocStart);
976 const char *endBuf = SM->getCharacterData(LocEnd);
977 for (const char *p = startBuf; p < endBuf; p++) {
978 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
979 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
980 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
981
982 }
983 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
984 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
985 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
986
987 }
988 }
989}
990
991void RewriteModernObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
992 SourceLocation LocStart = (*D.begin())->getLocStart();
993 if (LocStart.isInvalid())
994 llvm_unreachable("Invalid SourceLocation");
995 // FIXME: handle forward protocol that are declared across multiple lines.
996 ReplaceText(LocStart, 0, "// ");
997}
998
999void
1000RewriteModernObjC::RewriteForwardProtocolDecl(const llvm::SmallVector<Decl*, 8> &DG) {
1001 SourceLocation LocStart = DG[0]->getLocStart();
1002 if (LocStart.isInvalid())
1003 llvm_unreachable("Invalid SourceLocation");
1004 // FIXME: handle forward protocol that are declared across multiple lines.
1005 ReplaceText(LocStart, 0, "// ");
1006}
1007
1008void RewriteModernObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1009 const FunctionType *&FPRetType) {
1010 if (T->isObjCQualifiedIdType())
1011 ResultStr += "id";
1012 else if (T->isFunctionPointerType() ||
1013 T->isBlockPointerType()) {
1014 // needs special handling, since pointer-to-functions have special
1015 // syntax (where a decaration models use).
1016 QualType retType = T;
1017 QualType PointeeTy;
1018 if (const PointerType* PT = retType->getAs<PointerType>())
1019 PointeeTy = PT->getPointeeType();
1020 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
1021 PointeeTy = BPT->getPointeeType();
1022 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
1023 ResultStr += FPRetType->getResultType().getAsString(
1024 Context->getPrintingPolicy());
1025 ResultStr += "(*";
1026 }
1027 } else
1028 ResultStr += T.getAsString(Context->getPrintingPolicy());
1029}
1030
1031void RewriteModernObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1032 ObjCMethodDecl *OMD,
1033 std::string &ResultStr) {
1034 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1035 const FunctionType *FPRetType = 0;
1036 ResultStr += "\nstatic ";
1037 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
1038 ResultStr += " ";
1039
1040 // Unique method name
1041 std::string NameStr;
1042
1043 if (OMD->isInstanceMethod())
1044 NameStr += "_I_";
1045 else
1046 NameStr += "_C_";
1047
1048 NameStr += IDecl->getNameAsString();
1049 NameStr += "_";
1050
1051 if (ObjCCategoryImplDecl *CID =
1052 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
1053 NameStr += CID->getNameAsString();
1054 NameStr += "_";
1055 }
1056 // Append selector names, replacing ':' with '_'
1057 {
1058 std::string selString = OMD->getSelector().getAsString();
1059 int len = selString.size();
1060 for (int i = 0; i < len; i++)
1061 if (selString[i] == ':')
1062 selString[i] = '_';
1063 NameStr += selString;
1064 }
1065 // Remember this name for metadata emission
1066 MethodInternalNames[OMD] = NameStr;
1067 ResultStr += NameStr;
1068
1069 // Rewrite arguments
1070 ResultStr += "(";
1071
1072 // invisible arguments
1073 if (OMD->isInstanceMethod()) {
1074 QualType selfTy = Context->getObjCInterfaceType(IDecl);
1075 selfTy = Context->getPointerType(selfTy);
1076 if (!LangOpts.MicrosoftExt) {
1077 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
1078 ResultStr += "struct ";
1079 }
1080 // When rewriting for Microsoft, explicitly omit the structure name.
1081 ResultStr += IDecl->getNameAsString();
1082 ResultStr += " *";
1083 }
1084 else
1085 ResultStr += Context->getObjCClassType().getAsString(
1086 Context->getPrintingPolicy());
1087
1088 ResultStr += " self, ";
1089 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
1090 ResultStr += " _cmd";
1091
1092 // Method arguments.
1093 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1094 E = OMD->param_end(); PI != E; ++PI) {
1095 ParmVarDecl *PDecl = *PI;
1096 ResultStr += ", ";
1097 if (PDecl->getType()->isObjCQualifiedIdType()) {
1098 ResultStr += "id ";
1099 ResultStr += PDecl->getNameAsString();
1100 } else {
1101 std::string Name = PDecl->getNameAsString();
1102 QualType QT = PDecl->getType();
1103 // Make sure we convert "t (^)(...)" to "t (*)(...)".
1104 if (convertBlockPointerToFunctionPointer(QT))
1105 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
1106 else
1107 PDecl->getType().getAsStringInternal(Name, Context->getPrintingPolicy());
1108 ResultStr += Name;
1109 }
1110 }
1111 if (OMD->isVariadic())
1112 ResultStr += ", ...";
1113 ResultStr += ") ";
1114
1115 if (FPRetType) {
1116 ResultStr += ")"; // close the precedence "scope" for "*".
1117
1118 // Now, emit the argument types (if any).
1119 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
1120 ResultStr += "(";
1121 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1122 if (i) ResultStr += ", ";
1123 std::string ParamStr = FT->getArgType(i).getAsString(
1124 Context->getPrintingPolicy());
1125 ResultStr += ParamStr;
1126 }
1127 if (FT->isVariadic()) {
1128 if (FT->getNumArgs()) ResultStr += ", ";
1129 ResultStr += "...";
1130 }
1131 ResultStr += ")";
1132 } else {
1133 ResultStr += "()";
1134 }
1135 }
1136}
1137void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) {
1138 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1139 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
1140
1141 InsertText(IMD ? IMD->getLocStart() : CID->getLocStart(), "// ");
1142
1143 for (ObjCCategoryImplDecl::instmeth_iterator
1144 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1145 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
1146 I != E; ++I) {
1147 std::string ResultStr;
1148 ObjCMethodDecl *OMD = *I;
1149 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1150 SourceLocation LocStart = OMD->getLocStart();
1151 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1152
1153 const char *startBuf = SM->getCharacterData(LocStart);
1154 const char *endBuf = SM->getCharacterData(LocEnd);
1155 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1156 }
1157
1158 for (ObjCCategoryImplDecl::classmeth_iterator
1159 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1160 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
1161 I != E; ++I) {
1162 std::string ResultStr;
1163 ObjCMethodDecl *OMD = *I;
1164 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1165 SourceLocation LocStart = OMD->getLocStart();
1166 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1167
1168 const char *startBuf = SM->getCharacterData(LocStart);
1169 const char *endBuf = SM->getCharacterData(LocEnd);
1170 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1171 }
1172 for (ObjCCategoryImplDecl::propimpl_iterator
1173 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
1174 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
1175 I != E; ++I) {
1176 RewritePropertyImplDecl(*I, IMD, CID);
1177 }
1178
1179 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
1180}
1181
1182void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00001183 // Do not synthesize more than once.
1184 if (ObjCSynthesizedStructs.count(ClassDecl))
1185 return;
1186 // Make sure super class's are written before current class is written.
1187 ObjCInterfaceDecl *SuperClass = ClassDecl->getSuperClass();
1188 while (SuperClass) {
1189 RewriteInterfaceDecl(SuperClass);
1190 SuperClass = SuperClass->getSuperClass();
1191 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001192 std::string ResultStr;
1193 if (!ObjCForwardDecls.count(ClassDecl->getCanonicalDecl())) {
1194 // we haven't seen a forward decl - generate a typedef.
1195 ResultStr = "#ifndef _REWRITER_typedef_";
1196 ResultStr += ClassDecl->getNameAsString();
1197 ResultStr += "\n";
1198 ResultStr += "#define _REWRITER_typedef_";
1199 ResultStr += ClassDecl->getNameAsString();
1200 ResultStr += "\n";
1201 ResultStr += "typedef struct objc_object ";
1202 ResultStr += ClassDecl->getNameAsString();
1203 ResultStr += ";\n#endif\n";
1204 // Mark this typedef as having been generated.
1205 ObjCForwardDecls.insert(ClassDecl->getCanonicalDecl());
1206 }
1207 RewriteObjCInternalStruct(ClassDecl, ResultStr);
1208
1209 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
1210 E = ClassDecl->prop_end(); I != E; ++I)
1211 RewriteProperty(*I);
1212 for (ObjCInterfaceDecl::instmeth_iterator
1213 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
1214 I != E; ++I)
1215 RewriteMethodDeclaration(*I);
1216 for (ObjCInterfaceDecl::classmeth_iterator
1217 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
1218 I != E; ++I)
1219 RewriteMethodDeclaration(*I);
1220
1221 // Lastly, comment out the @end.
1222 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1223 "/* @end */");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00001224 // Mark this struct as having been generated.
1225 if (!ObjCSynthesizedStructs.insert(ClassDecl))
1226 llvm_unreachable("struct already synthesize- RewriteInterfaceDecl");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001227}
1228
1229Stmt *RewriteModernObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1230 SourceRange OldRange = PseudoOp->getSourceRange();
1231
1232 // We just magically know some things about the structure of this
1233 // expression.
1234 ObjCMessageExpr *OldMsg =
1235 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1236 PseudoOp->getNumSemanticExprs() - 1));
1237
1238 // Because the rewriter doesn't allow us to rewrite rewritten code,
1239 // we need to suppress rewriting the sub-statements.
1240 Expr *Base, *RHS;
1241 {
1242 DisableReplaceStmtScope S(*this);
1243
1244 // Rebuild the base expression if we have one.
1245 Base = 0;
1246 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1247 Base = OldMsg->getInstanceReceiver();
1248 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1249 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1250 }
1251
1252 // Rebuild the RHS.
1253 RHS = cast<BinaryOperator>(PseudoOp->getSyntacticForm())->getRHS();
1254 RHS = cast<OpaqueValueExpr>(RHS)->getSourceExpr();
1255 RHS = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(RHS));
1256 }
1257
1258 // TODO: avoid this copy.
1259 SmallVector<SourceLocation, 1> SelLocs;
1260 OldMsg->getSelectorLocs(SelLocs);
1261
1262 ObjCMessageExpr *NewMsg = 0;
1263 switch (OldMsg->getReceiverKind()) {
1264 case ObjCMessageExpr::Class:
1265 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1266 OldMsg->getValueKind(),
1267 OldMsg->getLeftLoc(),
1268 OldMsg->getClassReceiverTypeInfo(),
1269 OldMsg->getSelector(),
1270 SelLocs,
1271 OldMsg->getMethodDecl(),
1272 RHS,
1273 OldMsg->getRightLoc(),
1274 OldMsg->isImplicit());
1275 break;
1276
1277 case ObjCMessageExpr::Instance:
1278 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1279 OldMsg->getValueKind(),
1280 OldMsg->getLeftLoc(),
1281 Base,
1282 OldMsg->getSelector(),
1283 SelLocs,
1284 OldMsg->getMethodDecl(),
1285 RHS,
1286 OldMsg->getRightLoc(),
1287 OldMsg->isImplicit());
1288 break;
1289
1290 case ObjCMessageExpr::SuperClass:
1291 case ObjCMessageExpr::SuperInstance:
1292 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1293 OldMsg->getValueKind(),
1294 OldMsg->getLeftLoc(),
1295 OldMsg->getSuperLoc(),
1296 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1297 OldMsg->getSuperType(),
1298 OldMsg->getSelector(),
1299 SelLocs,
1300 OldMsg->getMethodDecl(),
1301 RHS,
1302 OldMsg->getRightLoc(),
1303 OldMsg->isImplicit());
1304 break;
1305 }
1306
1307 Stmt *Replacement = SynthMessageExpr(NewMsg);
1308 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1309 return Replacement;
1310}
1311
1312Stmt *RewriteModernObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1313 SourceRange OldRange = PseudoOp->getSourceRange();
1314
1315 // We just magically know some things about the structure of this
1316 // expression.
1317 ObjCMessageExpr *OldMsg =
1318 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1319
1320 // Because the rewriter doesn't allow us to rewrite rewritten code,
1321 // we need to suppress rewriting the sub-statements.
1322 Expr *Base = 0;
1323 {
1324 DisableReplaceStmtScope S(*this);
1325
1326 // Rebuild the base expression if we have one.
1327 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1328 Base = OldMsg->getInstanceReceiver();
1329 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1330 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1331 }
1332 }
1333
1334 // Intentionally empty.
1335 SmallVector<SourceLocation, 1> SelLocs;
1336 SmallVector<Expr*, 1> Args;
1337
1338 ObjCMessageExpr *NewMsg = 0;
1339 switch (OldMsg->getReceiverKind()) {
1340 case ObjCMessageExpr::Class:
1341 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1342 OldMsg->getValueKind(),
1343 OldMsg->getLeftLoc(),
1344 OldMsg->getClassReceiverTypeInfo(),
1345 OldMsg->getSelector(),
1346 SelLocs,
1347 OldMsg->getMethodDecl(),
1348 Args,
1349 OldMsg->getRightLoc(),
1350 OldMsg->isImplicit());
1351 break;
1352
1353 case ObjCMessageExpr::Instance:
1354 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1355 OldMsg->getValueKind(),
1356 OldMsg->getLeftLoc(),
1357 Base,
1358 OldMsg->getSelector(),
1359 SelLocs,
1360 OldMsg->getMethodDecl(),
1361 Args,
1362 OldMsg->getRightLoc(),
1363 OldMsg->isImplicit());
1364 break;
1365
1366 case ObjCMessageExpr::SuperClass:
1367 case ObjCMessageExpr::SuperInstance:
1368 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1369 OldMsg->getValueKind(),
1370 OldMsg->getLeftLoc(),
1371 OldMsg->getSuperLoc(),
1372 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1373 OldMsg->getSuperType(),
1374 OldMsg->getSelector(),
1375 SelLocs,
1376 OldMsg->getMethodDecl(),
1377 Args,
1378 OldMsg->getRightLoc(),
1379 OldMsg->isImplicit());
1380 break;
1381 }
1382
1383 Stmt *Replacement = SynthMessageExpr(NewMsg);
1384 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1385 return Replacement;
1386}
1387
1388/// SynthCountByEnumWithState - To print:
1389/// ((unsigned int (*)
1390/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1391/// (void *)objc_msgSend)((id)l_collection,
1392/// sel_registerName(
1393/// "countByEnumeratingWithState:objects:count:"),
1394/// &enumState,
1395/// (id *)__rw_items, (unsigned int)16)
1396///
1397void RewriteModernObjC::SynthCountByEnumWithState(std::string &buf) {
1398 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1399 "id *, unsigned int))(void *)objc_msgSend)";
1400 buf += "\n\t\t";
1401 buf += "((id)l_collection,\n\t\t";
1402 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1403 buf += "\n\t\t";
1404 buf += "&enumState, "
1405 "(id *)__rw_items, (unsigned int)16)";
1406}
1407
1408/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1409/// statement to exit to its outer synthesized loop.
1410///
1411Stmt *RewriteModernObjC::RewriteBreakStmt(BreakStmt *S) {
1412 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1413 return S;
1414 // replace break with goto __break_label
1415 std::string buf;
1416
1417 SourceLocation startLoc = S->getLocStart();
1418 buf = "goto __break_label_";
1419 buf += utostr(ObjCBcLabelNo.back());
1420 ReplaceText(startLoc, strlen("break"), buf);
1421
1422 return 0;
1423}
1424
1425/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1426/// statement to continue with its inner synthesized loop.
1427///
1428Stmt *RewriteModernObjC::RewriteContinueStmt(ContinueStmt *S) {
1429 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1430 return S;
1431 // replace continue with goto __continue_label
1432 std::string buf;
1433
1434 SourceLocation startLoc = S->getLocStart();
1435 buf = "goto __continue_label_";
1436 buf += utostr(ObjCBcLabelNo.back());
1437 ReplaceText(startLoc, strlen("continue"), buf);
1438
1439 return 0;
1440}
1441
1442/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
1443/// It rewrites:
1444/// for ( type elem in collection) { stmts; }
1445
1446/// Into:
1447/// {
1448/// type elem;
1449/// struct __objcFastEnumerationState enumState = { 0 };
1450/// id __rw_items[16];
1451/// id l_collection = (id)collection;
1452/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1453/// objects:__rw_items count:16];
1454/// if (limit) {
1455/// unsigned long startMutations = *enumState.mutationsPtr;
1456/// do {
1457/// unsigned long counter = 0;
1458/// do {
1459/// if (startMutations != *enumState.mutationsPtr)
1460/// objc_enumerationMutation(l_collection);
1461/// elem = (type)enumState.itemsPtr[counter++];
1462/// stmts;
1463/// __continue_label: ;
1464/// } while (counter < limit);
1465/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1466/// objects:__rw_items count:16]);
1467/// elem = nil;
1468/// __break_label: ;
1469/// }
1470/// else
1471/// elem = nil;
1472/// }
1473///
1474Stmt *RewriteModernObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1475 SourceLocation OrigEnd) {
1476 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1477 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1478 "ObjCForCollectionStmt Statement stack mismatch");
1479 assert(!ObjCBcLabelNo.empty() &&
1480 "ObjCForCollectionStmt - Label No stack empty");
1481
1482 SourceLocation startLoc = S->getLocStart();
1483 const char *startBuf = SM->getCharacterData(startLoc);
1484 StringRef elementName;
1485 std::string elementTypeAsString;
1486 std::string buf;
1487 buf = "\n{\n\t";
1488 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1489 // type elem;
1490 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1491 QualType ElementType = cast<ValueDecl>(D)->getType();
1492 if (ElementType->isObjCQualifiedIdType() ||
1493 ElementType->isObjCQualifiedInterfaceType())
1494 // Simply use 'id' for all qualified types.
1495 elementTypeAsString = "id";
1496 else
1497 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
1498 buf += elementTypeAsString;
1499 buf += " ";
1500 elementName = D->getName();
1501 buf += elementName;
1502 buf += ";\n\t";
1503 }
1504 else {
1505 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1506 elementName = DR->getDecl()->getName();
1507 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1508 if (VD->getType()->isObjCQualifiedIdType() ||
1509 VD->getType()->isObjCQualifiedInterfaceType())
1510 // Simply use 'id' for all qualified types.
1511 elementTypeAsString = "id";
1512 else
1513 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
1514 }
1515
1516 // struct __objcFastEnumerationState enumState = { 0 };
1517 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1518 // id __rw_items[16];
1519 buf += "id __rw_items[16];\n\t";
1520 // id l_collection = (id)
1521 buf += "id l_collection = (id)";
1522 // Find start location of 'collection' the hard way!
1523 const char *startCollectionBuf = startBuf;
1524 startCollectionBuf += 3; // skip 'for'
1525 startCollectionBuf = strchr(startCollectionBuf, '(');
1526 startCollectionBuf++; // skip '('
1527 // find 'in' and skip it.
1528 while (*startCollectionBuf != ' ' ||
1529 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1530 (*(startCollectionBuf+3) != ' ' &&
1531 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1532 startCollectionBuf++;
1533 startCollectionBuf += 3;
1534
1535 // Replace: "for (type element in" with string constructed thus far.
1536 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1537 // Replace ')' in for '(' type elem in collection ')' with ';'
1538 SourceLocation rightParenLoc = S->getRParenLoc();
1539 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1540 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
1541 buf = ";\n\t";
1542
1543 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1544 // objects:__rw_items count:16];
1545 // which is synthesized into:
1546 // unsigned int limit =
1547 // ((unsigned int (*)
1548 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1549 // (void *)objc_msgSend)((id)l_collection,
1550 // sel_registerName(
1551 // "countByEnumeratingWithState:objects:count:"),
1552 // (struct __objcFastEnumerationState *)&state,
1553 // (id *)__rw_items, (unsigned int)16);
1554 buf += "unsigned long limit =\n\t\t";
1555 SynthCountByEnumWithState(buf);
1556 buf += ";\n\t";
1557 /// if (limit) {
1558 /// unsigned long startMutations = *enumState.mutationsPtr;
1559 /// do {
1560 /// unsigned long counter = 0;
1561 /// do {
1562 /// if (startMutations != *enumState.mutationsPtr)
1563 /// objc_enumerationMutation(l_collection);
1564 /// elem = (type)enumState.itemsPtr[counter++];
1565 buf += "if (limit) {\n\t";
1566 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1567 buf += "do {\n\t\t";
1568 buf += "unsigned long counter = 0;\n\t\t";
1569 buf += "do {\n\t\t\t";
1570 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1571 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1572 buf += elementName;
1573 buf += " = (";
1574 buf += elementTypeAsString;
1575 buf += ")enumState.itemsPtr[counter++];";
1576 // Replace ')' in for '(' type elem in collection ')' with all of these.
1577 ReplaceText(lparenLoc, 1, buf);
1578
1579 /// __continue_label: ;
1580 /// } while (counter < limit);
1581 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1582 /// objects:__rw_items count:16]);
1583 /// elem = nil;
1584 /// __break_label: ;
1585 /// }
1586 /// else
1587 /// elem = nil;
1588 /// }
1589 ///
1590 buf = ";\n\t";
1591 buf += "__continue_label_";
1592 buf += utostr(ObjCBcLabelNo.back());
1593 buf += ": ;";
1594 buf += "\n\t\t";
1595 buf += "} while (counter < limit);\n\t";
1596 buf += "} while (limit = ";
1597 SynthCountByEnumWithState(buf);
1598 buf += ");\n\t";
1599 buf += elementName;
1600 buf += " = ((";
1601 buf += elementTypeAsString;
1602 buf += ")0);\n\t";
1603 buf += "__break_label_";
1604 buf += utostr(ObjCBcLabelNo.back());
1605 buf += ": ;\n\t";
1606 buf += "}\n\t";
1607 buf += "else\n\t\t";
1608 buf += elementName;
1609 buf += " = ((";
1610 buf += elementTypeAsString;
1611 buf += ")0);\n\t";
1612 buf += "}\n";
1613
1614 // Insert all these *after* the statement body.
1615 // FIXME: If this should support Obj-C++, support CXXTryStmt
1616 if (isa<CompoundStmt>(S->getBody())) {
1617 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
1618 InsertText(endBodyLoc, buf);
1619 } else {
1620 /* Need to treat single statements specially. For example:
1621 *
1622 * for (A *a in b) if (stuff()) break;
1623 * for (A *a in b) xxxyy;
1624 *
1625 * The following code simply scans ahead to the semi to find the actual end.
1626 */
1627 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1628 const char *semiBuf = strchr(stmtBuf, ';');
1629 assert(semiBuf && "Can't find ';'");
1630 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
1631 InsertText(endBodyLoc, buf);
1632 }
1633 Stmts.pop_back();
1634 ObjCBcLabelNo.pop_back();
1635 return 0;
1636}
1637
1638/// RewriteObjCSynchronizedStmt -
1639/// This routine rewrites @synchronized(expr) stmt;
1640/// into:
1641/// objc_sync_enter(expr);
1642/// @try stmt @finally { objc_sync_exit(expr); }
1643///
1644Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1645 // Get the start location and compute the semi location.
1646 SourceLocation startLoc = S->getLocStart();
1647 const char *startBuf = SM->getCharacterData(startLoc);
1648
1649 assert((*startBuf == '@') && "bogus @synchronized location");
1650
1651 std::string buf;
1652 buf = "objc_sync_enter((id)";
1653 const char *lparenBuf = startBuf;
1654 while (*lparenBuf != '(') lparenBuf++;
1655 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
1656 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1657 // the sync expression is typically a message expression that's already
1658 // been rewritten! (which implies the SourceLocation's are invalid).
1659 SourceLocation endLoc = S->getSynchBody()->getLocStart();
1660 const char *endBuf = SM->getCharacterData(endLoc);
1661 while (*endBuf != ')') endBuf--;
1662 SourceLocation rparenLoc = startLoc.getLocWithOffset(endBuf-startBuf);
1663 buf = ");\n";
1664 // declare a new scope with two variables, _stack and _rethrow.
1665 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1666 buf += "int buf[18/*32-bit i386*/];\n";
1667 buf += "char *pointers[4];} _stack;\n";
1668 buf += "id volatile _rethrow = 0;\n";
1669 buf += "objc_exception_try_enter(&_stack);\n";
1670 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
1671 ReplaceText(rparenLoc, 1, buf);
1672 startLoc = S->getSynchBody()->getLocEnd();
1673 startBuf = SM->getCharacterData(startLoc);
1674
1675 assert((*startBuf == '}') && "bogus @synchronized block");
1676 SourceLocation lastCurlyLoc = startLoc;
1677 buf = "}\nelse {\n";
1678 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1679 buf += "}\n";
1680 buf += "{ /* implicit finally clause */\n";
1681 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1682
1683 std::string syncBuf;
1684 syncBuf += " objc_sync_exit(";
1685
1686 Expr *syncExpr = S->getSynchExpr();
1687 CastKind CK = syncExpr->getType()->isObjCObjectPointerType()
1688 ? CK_BitCast :
1689 syncExpr->getType()->isBlockPointerType()
1690 ? CK_BlockPointerToObjCPointerCast
1691 : CK_CPointerToObjCPointerCast;
1692 syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
1693 CK, syncExpr);
1694 std::string syncExprBufS;
1695 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
1696 syncExpr->printPretty(syncExprBuf, *Context, 0,
1697 PrintingPolicy(LangOpts));
1698 syncBuf += syncExprBuf.str();
1699 syncBuf += ");";
1700
1701 buf += syncBuf;
1702 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
1703 buf += "}\n";
1704 buf += "}";
1705
1706 ReplaceText(lastCurlyLoc, 1, buf);
1707
1708 bool hasReturns = false;
1709 HasReturnStmts(S->getSynchBody(), hasReturns);
1710 if (hasReturns)
1711 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1712
1713 return 0;
1714}
1715
1716void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S)
1717{
1718 // Perform a bottom up traversal of all children.
1719 for (Stmt::child_range CI = S->children(); CI; ++CI)
1720 if (*CI)
1721 WarnAboutReturnGotoStmts(*CI);
1722
1723 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
1724 Diags.Report(Context->getFullLoc(S->getLocStart()),
1725 TryFinallyContainsReturnDiag);
1726 }
1727 return;
1728}
1729
1730void RewriteModernObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1731{
1732 // Perform a bottom up traversal of all children.
1733 for (Stmt::child_range CI = S->children(); CI; ++CI)
1734 if (*CI)
1735 HasReturnStmts(*CI, hasReturns);
1736
1737 if (isa<ReturnStmt>(S))
1738 hasReturns = true;
1739 return;
1740}
1741
1742void RewriteModernObjC::RewriteTryReturnStmts(Stmt *S) {
1743 // Perform a bottom up traversal of all children.
1744 for (Stmt::child_range CI = S->children(); CI; ++CI)
1745 if (*CI) {
1746 RewriteTryReturnStmts(*CI);
1747 }
1748 if (isa<ReturnStmt>(S)) {
1749 SourceLocation startLoc = S->getLocStart();
1750 const char *startBuf = SM->getCharacterData(startLoc);
1751
1752 const char *semiBuf = strchr(startBuf, ';');
1753 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1754 SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
1755
1756 std::string buf;
1757 buf = "{ objc_exception_try_exit(&_stack); return";
1758
1759 ReplaceText(startLoc, 6, buf);
1760 InsertText(onePastSemiLoc, "}");
1761 }
1762 return;
1763}
1764
1765void RewriteModernObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1766 // Perform a bottom up traversal of all children.
1767 for (Stmt::child_range CI = S->children(); CI; ++CI)
1768 if (*CI) {
1769 RewriteSyncReturnStmts(*CI, syncExitBuf);
1770 }
1771 if (isa<ReturnStmt>(S)) {
1772 SourceLocation startLoc = S->getLocStart();
1773 const char *startBuf = SM->getCharacterData(startLoc);
1774
1775 const char *semiBuf = strchr(startBuf, ';');
1776 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
1777 SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
1778
1779 std::string buf;
1780 buf = "{ objc_exception_try_exit(&_stack);";
1781 buf += syncExitBuf;
1782 buf += " return";
1783
1784 ReplaceText(startLoc, 6, buf);
1785 InsertText(onePastSemiLoc, "}");
1786 }
1787 return;
1788}
1789
1790Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
1791 // Get the start location and compute the semi location.
1792 SourceLocation startLoc = S->getLocStart();
1793 const char *startBuf = SM->getCharacterData(startLoc);
1794
1795 assert((*startBuf == '@') && "bogus @try location");
1796
1797 std::string buf;
1798 // declare a new scope with two variables, _stack and _rethrow.
1799 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1800 buf += "int buf[18/*32-bit i386*/];\n";
1801 buf += "char *pointers[4];} _stack;\n";
1802 buf += "id volatile _rethrow = 0;\n";
1803 buf += "objc_exception_try_enter(&_stack);\n";
1804 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
1805
1806 ReplaceText(startLoc, 4, buf);
1807
1808 startLoc = S->getTryBody()->getLocEnd();
1809 startBuf = SM->getCharacterData(startLoc);
1810
1811 assert((*startBuf == '}') && "bogus @try block");
1812
1813 SourceLocation lastCurlyLoc = startLoc;
1814 if (S->getNumCatchStmts()) {
1815 startLoc = startLoc.getLocWithOffset(1);
1816 buf = " /* @catch begin */ else {\n";
1817 buf += " id _caught = objc_exception_extract(&_stack);\n";
1818 buf += " objc_exception_try_enter (&_stack);\n";
1819 buf += " if (_setjmp(_stack.buf))\n";
1820 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1821 buf += " else { /* @catch continue */";
1822
1823 InsertText(startLoc, buf);
1824 } else { /* no catch list */
1825 buf = "}\nelse {\n";
1826 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1827 buf += "}";
1828 ReplaceText(lastCurlyLoc, 1, buf);
1829 }
1830 Stmt *lastCatchBody = 0;
1831 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1832 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
1833 VarDecl *catchDecl = Catch->getCatchParamDecl();
1834
1835 if (I == 0)
1836 buf = "if ("; // we are generating code for the first catch clause
1837 else
1838 buf = "else if (";
1839 startLoc = Catch->getLocStart();
1840 startBuf = SM->getCharacterData(startLoc);
1841
1842 assert((*startBuf == '@') && "bogus @catch location");
1843
1844 const char *lParenLoc = strchr(startBuf, '(');
1845
1846 if (Catch->hasEllipsis()) {
1847 // Now rewrite the body...
1848 lastCatchBody = Catch->getCatchBody();
1849 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1850 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1851 assert(*SM->getCharacterData(Catch->getRParenLoc()) == ')' &&
1852 "bogus @catch paren location");
1853 assert((*bodyBuf == '{') && "bogus @catch body location");
1854
1855 buf += "1) { id _tmp = _caught;";
1856 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
1857 } else if (catchDecl) {
1858 QualType t = catchDecl->getType();
1859 if (t == Context->getObjCIdType()) {
1860 buf += "1) { ";
1861 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
1862 } else if (const ObjCObjectPointerType *Ptr =
1863 t->getAs<ObjCObjectPointerType>()) {
1864 // Should be a pointer to a class.
1865 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1866 if (IDecl) {
1867 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
1868 buf += IDecl->getNameAsString();
1869 buf += "\"), (struct objc_object *)_caught)) { ";
1870 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
1871 }
1872 }
1873 // Now rewrite the body...
1874 lastCatchBody = Catch->getCatchBody();
1875 SourceLocation rParenLoc = Catch->getRParenLoc();
1876 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1877 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1878 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1879 assert((*rParenBuf == ')') && "bogus @catch paren location");
1880 assert((*bodyBuf == '{') && "bogus @catch body location");
1881
1882 // Here we replace ") {" with "= _caught;" (which initializes and
1883 // declares the @catch parameter).
1884 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;");
1885 } else {
1886 llvm_unreachable("@catch rewrite bug");
1887 }
1888 }
1889 // Complete the catch list...
1890 if (lastCatchBody) {
1891 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
1892 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1893 "bogus @catch body location");
1894
1895 // Insert the last (implicit) else clause *before* the right curly brace.
1896 bodyLoc = bodyLoc.getLocWithOffset(-1);
1897 buf = "} /* last catch end */\n";
1898 buf += "else {\n";
1899 buf += " _rethrow = _caught;\n";
1900 buf += " objc_exception_try_exit(&_stack);\n";
1901 buf += "} } /* @catch end */\n";
1902 if (!S->getFinallyStmt())
1903 buf += "}\n";
1904 InsertText(bodyLoc, buf);
1905
1906 // Set lastCurlyLoc
1907 lastCurlyLoc = lastCatchBody->getLocEnd();
1908 }
1909 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
1910 startLoc = finalStmt->getLocStart();
1911 startBuf = SM->getCharacterData(startLoc);
1912 assert((*startBuf == '@') && "bogus @finally start");
1913
1914 ReplaceText(startLoc, 8, "/* @finally */");
1915
1916 Stmt *body = finalStmt->getFinallyBody();
1917 SourceLocation startLoc = body->getLocStart();
1918 SourceLocation endLoc = body->getLocEnd();
1919 assert(*SM->getCharacterData(startLoc) == '{' &&
1920 "bogus @finally body location");
1921 assert(*SM->getCharacterData(endLoc) == '}' &&
1922 "bogus @finally body location");
1923
1924 startLoc = startLoc.getLocWithOffset(1);
1925 InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n");
1926 endLoc = endLoc.getLocWithOffset(-1);
1927 InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n");
1928
1929 // Set lastCurlyLoc
1930 lastCurlyLoc = body->getLocEnd();
1931
1932 // Now check for any return/continue/go statements within the @try.
1933 WarnAboutReturnGotoStmts(S->getTryBody());
1934 } else { /* no finally clause - make sure we synthesize an implicit one */
1935 buf = "{ /* implicit finally clause */\n";
1936 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1937 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1938 buf += "}";
1939 ReplaceText(lastCurlyLoc, 1, buf);
1940
1941 // Now check for any return/continue/go statements within the @try.
1942 // The implicit finally clause won't called if the @try contains any
1943 // jump statements.
1944 bool hasReturns = false;
1945 HasReturnStmts(S->getTryBody(), hasReturns);
1946 if (hasReturns)
1947 RewriteTryReturnStmts(S->getTryBody());
1948 }
1949 // Now emit the final closing curly brace...
1950 lastCurlyLoc = lastCurlyLoc.getLocWithOffset(1);
1951 InsertText(lastCurlyLoc, " } /* @try scope end */\n");
1952 return 0;
1953}
1954
1955// This can't be done with ReplaceStmt(S, ThrowExpr), since
1956// the throw expression is typically a message expression that's already
1957// been rewritten! (which implies the SourceLocation's are invalid).
1958Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
1959 // Get the start location and compute the semi location.
1960 SourceLocation startLoc = S->getLocStart();
1961 const char *startBuf = SM->getCharacterData(startLoc);
1962
1963 assert((*startBuf == '@') && "bogus @throw location");
1964
1965 std::string buf;
1966 /* void objc_exception_throw(id) __attribute__((noreturn)); */
1967 if (S->getThrowExpr())
1968 buf = "objc_exception_throw(";
1969 else // add an implicit argument
1970 buf = "objc_exception_throw(_caught";
1971
1972 // handle "@ throw" correctly.
1973 const char *wBuf = strchr(startBuf, 'w');
1974 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1975 ReplaceText(startLoc, wBuf-startBuf+1, buf);
1976
1977 const char *semiBuf = strchr(startBuf, ';');
1978 assert((*semiBuf == ';') && "@throw: can't find ';'");
1979 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
1980 ReplaceText(semiLoc, 1, ");");
1981 return 0;
1982}
1983
1984Stmt *RewriteModernObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
1985 // Create a new string expression.
1986 QualType StrType = Context->getPointerType(Context->CharTy);
1987 std::string StrEncoding;
1988 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
1989 Expr *Replacement = StringLiteral::Create(*Context, StrEncoding,
1990 StringLiteral::Ascii, false,
1991 StrType, SourceLocation());
1992 ReplaceStmt(Exp, Replacement);
1993
1994 // Replace this subexpr in the parent.
1995 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
1996 return Replacement;
1997}
1998
1999Stmt *RewriteModernObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
2000 if (!SelGetUidFunctionDecl)
2001 SynthSelGetUidFunctionDecl();
2002 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2003 // Create a call to sel_registerName("selName").
2004 SmallVector<Expr*, 8> SelExprs;
2005 QualType argType = Context->getPointerType(Context->CharTy);
2006 SelExprs.push_back(StringLiteral::Create(*Context,
2007 Exp->getSelector().getAsString(),
2008 StringLiteral::Ascii, false,
2009 argType, SourceLocation()));
2010 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2011 &SelExprs[0], SelExprs.size());
2012 ReplaceStmt(Exp, SelExp);
2013 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2014 return SelExp;
2015}
2016
2017CallExpr *RewriteModernObjC::SynthesizeCallToFunctionDecl(
2018 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2019 SourceLocation EndLoc) {
2020 // Get the type, we will need to reference it in a couple spots.
2021 QualType msgSendType = FD->getType();
2022
2023 // Create a reference to the objc_msgSend() declaration.
2024 DeclRefExpr *DRE =
2025 new (Context) DeclRefExpr(FD, msgSendType, VK_LValue, SourceLocation());
2026
2027 // Now, we cast the reference to a pointer to the objc_msgSend type.
2028 QualType pToFunc = Context->getPointerType(msgSendType);
2029 ImplicitCastExpr *ICE =
2030 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
2031 DRE, 0, VK_RValue);
2032
2033 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2034
2035 CallExpr *Exp =
2036 new (Context) CallExpr(*Context, ICE, args, nargs,
2037 FT->getCallResultType(*Context),
2038 VK_RValue, EndLoc);
2039 return Exp;
2040}
2041
2042static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2043 const char *&startRef, const char *&endRef) {
2044 while (startBuf < endBuf) {
2045 if (*startBuf == '<')
2046 startRef = startBuf; // mark the start.
2047 if (*startBuf == '>') {
2048 if (startRef && *startRef == '<') {
2049 endRef = startBuf; // mark the end.
2050 return true;
2051 }
2052 return false;
2053 }
2054 startBuf++;
2055 }
2056 return false;
2057}
2058
2059static void scanToNextArgument(const char *&argRef) {
2060 int angle = 0;
2061 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2062 if (*argRef == '<')
2063 angle++;
2064 else if (*argRef == '>')
2065 angle--;
2066 argRef++;
2067 }
2068 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2069}
2070
2071bool RewriteModernObjC::needToScanForQualifiers(QualType T) {
2072 if (T->isObjCQualifiedIdType())
2073 return true;
2074 if (const PointerType *PT = T->getAs<PointerType>()) {
2075 if (PT->getPointeeType()->isObjCQualifiedIdType())
2076 return true;
2077 }
2078 if (T->isObjCObjectPointerType()) {
2079 T = T->getPointeeType();
2080 return T->isObjCQualifiedInterfaceType();
2081 }
2082 if (T->isArrayType()) {
2083 QualType ElemTy = Context->getBaseElementType(T);
2084 return needToScanForQualifiers(ElemTy);
2085 }
2086 return false;
2087}
2088
2089void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2090 QualType Type = E->getType();
2091 if (needToScanForQualifiers(Type)) {
2092 SourceLocation Loc, EndLoc;
2093
2094 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2095 Loc = ECE->getLParenLoc();
2096 EndLoc = ECE->getRParenLoc();
2097 } else {
2098 Loc = E->getLocStart();
2099 EndLoc = E->getLocEnd();
2100 }
2101 // This will defend against trying to rewrite synthesized expressions.
2102 if (Loc.isInvalid() || EndLoc.isInvalid())
2103 return;
2104
2105 const char *startBuf = SM->getCharacterData(Loc);
2106 const char *endBuf = SM->getCharacterData(EndLoc);
2107 const char *startRef = 0, *endRef = 0;
2108 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2109 // Get the locations of the startRef, endRef.
2110 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2111 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2112 // Comment out the protocol references.
2113 InsertText(LessLoc, "/*");
2114 InsertText(GreaterLoc, "*/");
2115 }
2116 }
2117}
2118
2119void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2120 SourceLocation Loc;
2121 QualType Type;
2122 const FunctionProtoType *proto = 0;
2123 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2124 Loc = VD->getLocation();
2125 Type = VD->getType();
2126 }
2127 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2128 Loc = FD->getLocation();
2129 // Check for ObjC 'id' and class types that have been adorned with protocol
2130 // information (id<p>, C<p>*). The protocol references need to be rewritten!
2131 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2132 assert(funcType && "missing function type");
2133 proto = dyn_cast<FunctionProtoType>(funcType);
2134 if (!proto)
2135 return;
2136 Type = proto->getResultType();
2137 }
2138 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2139 Loc = FD->getLocation();
2140 Type = FD->getType();
2141 }
2142 else
2143 return;
2144
2145 if (needToScanForQualifiers(Type)) {
2146 // Since types are unique, we need to scan the buffer.
2147
2148 const char *endBuf = SM->getCharacterData(Loc);
2149 const char *startBuf = endBuf;
2150 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
2151 startBuf--; // scan backward (from the decl location) for return type.
2152 const char *startRef = 0, *endRef = 0;
2153 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2154 // Get the locations of the startRef, endRef.
2155 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2156 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2157 // Comment out the protocol references.
2158 InsertText(LessLoc, "/*");
2159 InsertText(GreaterLoc, "*/");
2160 }
2161 }
2162 if (!proto)
2163 return; // most likely, was a variable
2164 // Now check arguments.
2165 const char *startBuf = SM->getCharacterData(Loc);
2166 const char *startFuncBuf = startBuf;
2167 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2168 if (needToScanForQualifiers(proto->getArgType(i))) {
2169 // Since types are unique, we need to scan the buffer.
2170
2171 const char *endBuf = startBuf;
2172 // scan forward (from the decl location) for argument types.
2173 scanToNextArgument(endBuf);
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 =
2178 Loc.getLocWithOffset(startRef-startFuncBuf);
2179 SourceLocation GreaterLoc =
2180 Loc.getLocWithOffset(endRef-startFuncBuf+1);
2181 // Comment out the protocol references.
2182 InsertText(LessLoc, "/*");
2183 InsertText(GreaterLoc, "*/");
2184 }
2185 startBuf = ++endBuf;
2186 }
2187 else {
2188 // If the function name is derived from a macro expansion, then the
2189 // argument buffer will not follow the name. Need to speak with Chris.
2190 while (*startBuf && *startBuf != ')' && *startBuf != ',')
2191 startBuf++; // scan forward (from the decl location) for argument types.
2192 startBuf++;
2193 }
2194 }
2195}
2196
2197void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) {
2198 QualType QT = ND->getType();
2199 const Type* TypePtr = QT->getAs<Type>();
2200 if (!isa<TypeOfExprType>(TypePtr))
2201 return;
2202 while (isa<TypeOfExprType>(TypePtr)) {
2203 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2204 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2205 TypePtr = QT->getAs<Type>();
2206 }
2207 // FIXME. This will not work for multiple declarators; as in:
2208 // __typeof__(a) b,c,d;
2209 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2210 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2211 const char *startBuf = SM->getCharacterData(DeclLoc);
2212 if (ND->getInit()) {
2213 std::string Name(ND->getNameAsString());
2214 TypeAsString += " " + Name + " = ";
2215 Expr *E = ND->getInit();
2216 SourceLocation startLoc;
2217 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2218 startLoc = ECE->getLParenLoc();
2219 else
2220 startLoc = E->getLocStart();
2221 startLoc = SM->getExpansionLoc(startLoc);
2222 const char *endBuf = SM->getCharacterData(startLoc);
2223 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2224 }
2225 else {
2226 SourceLocation X = ND->getLocEnd();
2227 X = SM->getExpansionLoc(X);
2228 const char *endBuf = SM->getCharacterData(X);
2229 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2230 }
2231}
2232
2233// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2234void RewriteModernObjC::SynthSelGetUidFunctionDecl() {
2235 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2236 SmallVector<QualType, 16> ArgTys;
2237 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2238 QualType getFuncType =
2239 getSimpleFunctionType(Context->getObjCSelType(), &ArgTys[0], ArgTys.size());
2240 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2241 SourceLocation(),
2242 SourceLocation(),
2243 SelGetUidIdent, getFuncType, 0,
2244 SC_Extern,
2245 SC_None, false);
2246}
2247
2248void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2249 // declared in <objc/objc.h>
2250 if (FD->getIdentifier() &&
2251 FD->getName() == "sel_registerName") {
2252 SelGetUidFunctionDecl = FD;
2253 return;
2254 }
2255 RewriteObjCQualifiedInterfaceTypes(FD);
2256}
2257
2258void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2259 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2260 const char *argPtr = TypeString.c_str();
2261 if (!strchr(argPtr, '^')) {
2262 Str += TypeString;
2263 return;
2264 }
2265 while (*argPtr) {
2266 Str += (*argPtr == '^' ? '*' : *argPtr);
2267 argPtr++;
2268 }
2269}
2270
2271// FIXME. Consolidate this routine with RewriteBlockPointerType.
2272void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2273 ValueDecl *VD) {
2274 QualType Type = VD->getType();
2275 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2276 const char *argPtr = TypeString.c_str();
2277 int paren = 0;
2278 while (*argPtr) {
2279 switch (*argPtr) {
2280 case '(':
2281 Str += *argPtr;
2282 paren++;
2283 break;
2284 case ')':
2285 Str += *argPtr;
2286 paren--;
2287 break;
2288 case '^':
2289 Str += '*';
2290 if (paren == 1)
2291 Str += VD->getNameAsString();
2292 break;
2293 default:
2294 Str += *argPtr;
2295 break;
2296 }
2297 argPtr++;
2298 }
2299}
2300
2301
2302void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2303 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2304 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2305 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2306 if (!proto)
2307 return;
2308 QualType Type = proto->getResultType();
2309 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2310 FdStr += " ";
2311 FdStr += FD->getName();
2312 FdStr += "(";
2313 unsigned numArgs = proto->getNumArgs();
2314 for (unsigned i = 0; i < numArgs; i++) {
2315 QualType ArgType = proto->getArgType(i);
2316 RewriteBlockPointerType(FdStr, ArgType);
2317 if (i+1 < numArgs)
2318 FdStr += ", ";
2319 }
2320 FdStr += ");\n";
2321 InsertText(FunLocStart, FdStr);
2322 CurFunctionDeclToDeclareForBlock = 0;
2323}
2324
2325// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
2326void RewriteModernObjC::SynthSuperContructorFunctionDecl() {
2327 if (SuperContructorFunctionDecl)
2328 return;
2329 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2330 SmallVector<QualType, 16> ArgTys;
2331 QualType argT = Context->getObjCIdType();
2332 assert(!argT.isNull() && "Can't find 'id' type");
2333 ArgTys.push_back(argT);
2334 ArgTys.push_back(argT);
2335 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2336 &ArgTys[0], ArgTys.size());
2337 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2338 SourceLocation(),
2339 SourceLocation(),
2340 msgSendIdent, msgSendType, 0,
2341 SC_Extern,
2342 SC_None, false);
2343}
2344
2345// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2346void RewriteModernObjC::SynthMsgSendFunctionDecl() {
2347 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2348 SmallVector<QualType, 16> ArgTys;
2349 QualType argT = Context->getObjCIdType();
2350 assert(!argT.isNull() && "Can't find 'id' type");
2351 ArgTys.push_back(argT);
2352 argT = Context->getObjCSelType();
2353 assert(!argT.isNull() && "Can't find 'SEL' type");
2354 ArgTys.push_back(argT);
2355 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2356 &ArgTys[0], ArgTys.size(),
2357 true /*isVariadic*/);
2358 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2359 SourceLocation(),
2360 SourceLocation(),
2361 msgSendIdent, msgSendType, 0,
2362 SC_Extern,
2363 SC_None, false);
2364}
2365
2366// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
2367void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() {
2368 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2369 SmallVector<QualType, 16> ArgTys;
2370 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2371 SourceLocation(), SourceLocation(),
2372 &Context->Idents.get("objc_super"));
2373 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2374 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2375 ArgTys.push_back(argT);
2376 argT = Context->getObjCSelType();
2377 assert(!argT.isNull() && "Can't find 'SEL' type");
2378 ArgTys.push_back(argT);
2379 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2380 &ArgTys[0], ArgTys.size(),
2381 true /*isVariadic*/);
2382 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2383 SourceLocation(),
2384 SourceLocation(),
2385 msgSendIdent, msgSendType, 0,
2386 SC_Extern,
2387 SC_None, false);
2388}
2389
2390// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2391void RewriteModernObjC::SynthMsgSendStretFunctionDecl() {
2392 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2393 SmallVector<QualType, 16> ArgTys;
2394 QualType argT = Context->getObjCIdType();
2395 assert(!argT.isNull() && "Can't find 'id' type");
2396 ArgTys.push_back(argT);
2397 argT = Context->getObjCSelType();
2398 assert(!argT.isNull() && "Can't find 'SEL' type");
2399 ArgTys.push_back(argT);
2400 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2401 &ArgTys[0], ArgTys.size(),
2402 true /*isVariadic*/);
2403 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2404 SourceLocation(),
2405 SourceLocation(),
2406 msgSendIdent, msgSendType, 0,
2407 SC_Extern,
2408 SC_None, false);
2409}
2410
2411// SynthMsgSendSuperStretFunctionDecl -
2412// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
2413void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() {
2414 IdentifierInfo *msgSendIdent =
2415 &Context->Idents.get("objc_msgSendSuper_stret");
2416 SmallVector<QualType, 16> ArgTys;
2417 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2418 SourceLocation(), SourceLocation(),
2419 &Context->Idents.get("objc_super"));
2420 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2421 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2422 ArgTys.push_back(argT);
2423 argT = Context->getObjCSelType();
2424 assert(!argT.isNull() && "Can't find 'SEL' type");
2425 ArgTys.push_back(argT);
2426 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2427 &ArgTys[0], ArgTys.size(),
2428 true /*isVariadic*/);
2429 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2430 SourceLocation(),
2431 SourceLocation(),
2432 msgSendIdent, msgSendType, 0,
2433 SC_Extern,
2434 SC_None, false);
2435}
2436
2437// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2438void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() {
2439 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2440 SmallVector<QualType, 16> ArgTys;
2441 QualType argT = Context->getObjCIdType();
2442 assert(!argT.isNull() && "Can't find 'id' type");
2443 ArgTys.push_back(argT);
2444 argT = Context->getObjCSelType();
2445 assert(!argT.isNull() && "Can't find 'SEL' type");
2446 ArgTys.push_back(argT);
2447 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2448 &ArgTys[0], ArgTys.size(),
2449 true /*isVariadic*/);
2450 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2451 SourceLocation(),
2452 SourceLocation(),
2453 msgSendIdent, msgSendType, 0,
2454 SC_Extern,
2455 SC_None, false);
2456}
2457
2458// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
2459void RewriteModernObjC::SynthGetClassFunctionDecl() {
2460 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2461 SmallVector<QualType, 16> ArgTys;
2462 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2463 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2464 &ArgTys[0], ArgTys.size());
2465 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2466 SourceLocation(),
2467 SourceLocation(),
2468 getClassIdent, getClassType, 0,
2469 SC_Extern,
2470 SC_None, false);
2471}
2472
2473// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2474void RewriteModernObjC::SynthGetSuperClassFunctionDecl() {
2475 IdentifierInfo *getSuperClassIdent =
2476 &Context->Idents.get("class_getSuperclass");
2477 SmallVector<QualType, 16> ArgTys;
2478 ArgTys.push_back(Context->getObjCClassType());
2479 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2480 &ArgTys[0], ArgTys.size());
2481 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2482 SourceLocation(),
2483 SourceLocation(),
2484 getSuperClassIdent,
2485 getClassType, 0,
2486 SC_Extern,
2487 SC_None,
2488 false);
2489}
2490
2491// SynthGetMetaClassFunctionDecl - id objc_getMetaClass(const char *name);
2492void RewriteModernObjC::SynthGetMetaClassFunctionDecl() {
2493 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2494 SmallVector<QualType, 16> ArgTys;
2495 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2496 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2497 &ArgTys[0], ArgTys.size());
2498 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2499 SourceLocation(),
2500 SourceLocation(),
2501 getClassIdent, getClassType, 0,
2502 SC_Extern,
2503 SC_None, false);
2504}
2505
2506Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
2507 QualType strType = getConstantStringStructType();
2508
2509 std::string S = "__NSConstantStringImpl_";
2510
2511 std::string tmpName = InFileName;
2512 unsigned i;
2513 for (i=0; i < tmpName.length(); i++) {
2514 char c = tmpName.at(i);
2515 // replace any non alphanumeric characters with '_'.
2516 if (!isalpha(c) && (c < '0' || c > '9'))
2517 tmpName[i] = '_';
2518 }
2519 S += tmpName;
2520 S += "_";
2521 S += utostr(NumObjCStringLiterals++);
2522
2523 Preamble += "static __NSConstantStringImpl " + S;
2524 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2525 Preamble += "0x000007c8,"; // utf8_str
2526 // The pretty printer for StringLiteral handles escape characters properly.
2527 std::string prettyBufS;
2528 llvm::raw_string_ostream prettyBuf(prettyBufS);
2529 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2530 PrintingPolicy(LangOpts));
2531 Preamble += prettyBuf.str();
2532 Preamble += ",";
2533 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2534
2535 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2536 SourceLocation(), &Context->Idents.get(S),
2537 strType, 0, SC_Static, SC_None);
2538 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, VK_LValue,
2539 SourceLocation());
2540 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
2541 Context->getPointerType(DRE->getType()),
2542 VK_RValue, OK_Ordinary,
2543 SourceLocation());
2544 // cast to NSConstantString *
2545 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2546 CK_CPointerToObjCPointerCast, Unop);
2547 ReplaceStmt(Exp, cast);
2548 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2549 return cast;
2550}
2551
2552// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
2553QualType RewriteModernObjC::getSuperStructType() {
2554 if (!SuperStructDecl) {
2555 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2556 SourceLocation(), SourceLocation(),
2557 &Context->Idents.get("objc_super"));
2558 QualType FieldTypes[2];
2559
2560 // struct objc_object *receiver;
2561 FieldTypes[0] = Context->getObjCIdType();
2562 // struct objc_class *super;
2563 FieldTypes[1] = Context->getObjCClassType();
2564
2565 // Create fields
2566 for (unsigned i = 0; i < 2; ++i) {
2567 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2568 SourceLocation(),
2569 SourceLocation(), 0,
2570 FieldTypes[i], 0,
2571 /*BitWidth=*/0,
2572 /*Mutable=*/false,
2573 /*HasInit=*/false));
2574 }
2575
2576 SuperStructDecl->completeDefinition();
2577 }
2578 return Context->getTagDeclType(SuperStructDecl);
2579}
2580
2581QualType RewriteModernObjC::getConstantStringStructType() {
2582 if (!ConstantStringDecl) {
2583 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2584 SourceLocation(), SourceLocation(),
2585 &Context->Idents.get("__NSConstantStringImpl"));
2586 QualType FieldTypes[4];
2587
2588 // struct objc_object *receiver;
2589 FieldTypes[0] = Context->getObjCIdType();
2590 // int flags;
2591 FieldTypes[1] = Context->IntTy;
2592 // char *str;
2593 FieldTypes[2] = Context->getPointerType(Context->CharTy);
2594 // long length;
2595 FieldTypes[3] = Context->LongTy;
2596
2597 // Create fields
2598 for (unsigned i = 0; i < 4; ++i) {
2599 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2600 ConstantStringDecl,
2601 SourceLocation(),
2602 SourceLocation(), 0,
2603 FieldTypes[i], 0,
2604 /*BitWidth=*/0,
2605 /*Mutable=*/true,
2606 /*HasInit=*/false));
2607 }
2608
2609 ConstantStringDecl->completeDefinition();
2610 }
2611 return Context->getTagDeclType(ConstantStringDecl);
2612}
2613
2614Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2615 SourceLocation StartLoc,
2616 SourceLocation EndLoc) {
2617 if (!SelGetUidFunctionDecl)
2618 SynthSelGetUidFunctionDecl();
2619 if (!MsgSendFunctionDecl)
2620 SynthMsgSendFunctionDecl();
2621 if (!MsgSendSuperFunctionDecl)
2622 SynthMsgSendSuperFunctionDecl();
2623 if (!MsgSendStretFunctionDecl)
2624 SynthMsgSendStretFunctionDecl();
2625 if (!MsgSendSuperStretFunctionDecl)
2626 SynthMsgSendSuperStretFunctionDecl();
2627 if (!MsgSendFpretFunctionDecl)
2628 SynthMsgSendFpretFunctionDecl();
2629 if (!GetClassFunctionDecl)
2630 SynthGetClassFunctionDecl();
2631 if (!GetSuperClassFunctionDecl)
2632 SynthGetSuperClassFunctionDecl();
2633 if (!GetMetaClassFunctionDecl)
2634 SynthGetMetaClassFunctionDecl();
2635
2636 // default to objc_msgSend().
2637 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2638 // May need to use objc_msgSend_stret() as well.
2639 FunctionDecl *MsgSendStretFlavor = 0;
2640 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2641 QualType resultType = mDecl->getResultType();
2642 if (resultType->isRecordType())
2643 MsgSendStretFlavor = MsgSendStretFunctionDecl;
2644 else if (resultType->isRealFloatingType())
2645 MsgSendFlavor = MsgSendFpretFunctionDecl;
2646 }
2647
2648 // Synthesize a call to objc_msgSend().
2649 SmallVector<Expr*, 8> MsgExprs;
2650 switch (Exp->getReceiverKind()) {
2651 case ObjCMessageExpr::SuperClass: {
2652 MsgSendFlavor = MsgSendSuperFunctionDecl;
2653 if (MsgSendStretFlavor)
2654 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2655 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2656
2657 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
2658
2659 SmallVector<Expr*, 4> InitExprs;
2660
2661 // set the receiver to self, the first argument to all methods.
2662 InitExprs.push_back(
2663 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2664 CK_BitCast,
2665 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
2666 Context->getObjCIdType(),
2667 VK_RValue,
2668 SourceLocation()))
2669 ); // set the 'receiver'.
2670
2671 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2672 SmallVector<Expr*, 8> ClsExprs;
2673 QualType argType = Context->getPointerType(Context->CharTy);
2674 ClsExprs.push_back(StringLiteral::Create(*Context,
2675 ClassDecl->getIdentifier()->getName(),
2676 StringLiteral::Ascii, false,
2677 argType, SourceLocation()));
2678 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2679 &ClsExprs[0],
2680 ClsExprs.size(),
2681 StartLoc,
2682 EndLoc);
2683 // (Class)objc_getClass("CurrentClass")
2684 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2685 Context->getObjCClassType(),
2686 CK_BitCast, Cls);
2687 ClsExprs.clear();
2688 ClsExprs.push_back(ArgExpr);
2689 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2690 &ClsExprs[0], ClsExprs.size(),
2691 StartLoc, EndLoc);
2692
2693 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2694 // To turn off a warning, type-cast to 'id'
2695 InitExprs.push_back( // set 'super class', using class_getSuperclass().
2696 NoTypeInfoCStyleCastExpr(Context,
2697 Context->getObjCIdType(),
2698 CK_BitCast, Cls));
2699 // struct objc_super
2700 QualType superType = getSuperStructType();
2701 Expr *SuperRep;
2702
2703 if (LangOpts.MicrosoftExt) {
2704 SynthSuperContructorFunctionDecl();
2705 // Simulate a contructor call...
2706 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
2707 superType, VK_LValue,
2708 SourceLocation());
2709 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2710 InitExprs.size(),
2711 superType, VK_LValue,
2712 SourceLocation());
2713 // The code for super is a little tricky to prevent collision with
2714 // the structure definition in the header. The rewriter has it's own
2715 // internal definition (__rw_objc_super) that is uses. This is why
2716 // we need the cast below. For example:
2717 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2718 //
2719 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
2720 Context->getPointerType(SuperRep->getType()),
2721 VK_RValue, OK_Ordinary,
2722 SourceLocation());
2723 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2724 Context->getPointerType(superType),
2725 CK_BitCast, SuperRep);
2726 } else {
2727 // (struct objc_super) { <exprs from above> }
2728 InitListExpr *ILE =
2729 new (Context) InitListExpr(*Context, SourceLocation(),
2730 &InitExprs[0], InitExprs.size(),
2731 SourceLocation());
2732 TypeSourceInfo *superTInfo
2733 = Context->getTrivialTypeSourceInfo(superType);
2734 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2735 superType, VK_LValue,
2736 ILE, false);
2737 // struct objc_super *
2738 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
2739 Context->getPointerType(SuperRep->getType()),
2740 VK_RValue, OK_Ordinary,
2741 SourceLocation());
2742 }
2743 MsgExprs.push_back(SuperRep);
2744 break;
2745 }
2746
2747 case ObjCMessageExpr::Class: {
2748 SmallVector<Expr*, 8> ClsExprs;
2749 QualType argType = Context->getPointerType(Context->CharTy);
2750 ObjCInterfaceDecl *Class
2751 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
2752 IdentifierInfo *clsName = Class->getIdentifier();
2753 ClsExprs.push_back(StringLiteral::Create(*Context,
2754 clsName->getName(),
2755 StringLiteral::Ascii, false,
2756 argType, SourceLocation()));
2757 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2758 &ClsExprs[0],
2759 ClsExprs.size(),
2760 StartLoc, EndLoc);
2761 MsgExprs.push_back(Cls);
2762 break;
2763 }
2764
2765 case ObjCMessageExpr::SuperInstance:{
2766 MsgSendFlavor = MsgSendSuperFunctionDecl;
2767 if (MsgSendStretFlavor)
2768 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2769 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2770 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
2771 SmallVector<Expr*, 4> InitExprs;
2772
2773 InitExprs.push_back(
2774 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2775 CK_BitCast,
2776 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
2777 Context->getObjCIdType(),
2778 VK_RValue, SourceLocation()))
2779 ); // set the 'receiver'.
2780
2781 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2782 SmallVector<Expr*, 8> ClsExprs;
2783 QualType argType = Context->getPointerType(Context->CharTy);
2784 ClsExprs.push_back(StringLiteral::Create(*Context,
2785 ClassDecl->getIdentifier()->getName(),
2786 StringLiteral::Ascii, false, argType,
2787 SourceLocation()));
2788 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2789 &ClsExprs[0],
2790 ClsExprs.size(),
2791 StartLoc, EndLoc);
2792 // (Class)objc_getClass("CurrentClass")
2793 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2794 Context->getObjCClassType(),
2795 CK_BitCast, Cls);
2796 ClsExprs.clear();
2797 ClsExprs.push_back(ArgExpr);
2798 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2799 &ClsExprs[0], ClsExprs.size(),
2800 StartLoc, EndLoc);
2801
2802 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2803 // To turn off a warning, type-cast to 'id'
2804 InitExprs.push_back(
2805 // set 'super class', using class_getSuperclass().
2806 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2807 CK_BitCast, Cls));
2808 // struct objc_super
2809 QualType superType = getSuperStructType();
2810 Expr *SuperRep;
2811
2812 if (LangOpts.MicrosoftExt) {
2813 SynthSuperContructorFunctionDecl();
2814 // Simulate a contructor call...
2815 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
2816 superType, VK_LValue,
2817 SourceLocation());
2818 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2819 InitExprs.size(),
2820 superType, VK_LValue, SourceLocation());
2821 // The code for super is a little tricky to prevent collision with
2822 // the structure definition in the header. The rewriter has it's own
2823 // internal definition (__rw_objc_super) that is uses. This is why
2824 // we need the cast below. For example:
2825 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2826 //
2827 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
2828 Context->getPointerType(SuperRep->getType()),
2829 VK_RValue, OK_Ordinary,
2830 SourceLocation());
2831 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2832 Context->getPointerType(superType),
2833 CK_BitCast, SuperRep);
2834 } else {
2835 // (struct objc_super) { <exprs from above> }
2836 InitListExpr *ILE =
2837 new (Context) InitListExpr(*Context, SourceLocation(),
2838 &InitExprs[0], InitExprs.size(),
2839 SourceLocation());
2840 TypeSourceInfo *superTInfo
2841 = Context->getTrivialTypeSourceInfo(superType);
2842 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2843 superType, VK_RValue, ILE,
2844 false);
2845 }
2846 MsgExprs.push_back(SuperRep);
2847 break;
2848 }
2849
2850 case ObjCMessageExpr::Instance: {
2851 // Remove all type-casts because it may contain objc-style types; e.g.
2852 // Foo<Proto> *.
2853 Expr *recExpr = Exp->getInstanceReceiver();
2854 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
2855 recExpr = CE->getSubExpr();
2856 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
2857 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
2858 ? CK_BlockPointerToObjCPointerCast
2859 : CK_CPointerToObjCPointerCast;
2860
2861 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2862 CK, recExpr);
2863 MsgExprs.push_back(recExpr);
2864 break;
2865 }
2866 }
2867
2868 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
2869 SmallVector<Expr*, 8> SelExprs;
2870 QualType argType = Context->getPointerType(Context->CharTy);
2871 SelExprs.push_back(StringLiteral::Create(*Context,
2872 Exp->getSelector().getAsString(),
2873 StringLiteral::Ascii, false,
2874 argType, SourceLocation()));
2875 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2876 &SelExprs[0], SelExprs.size(),
2877 StartLoc,
2878 EndLoc);
2879 MsgExprs.push_back(SelExp);
2880
2881 // Now push any user supplied arguments.
2882 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
2883 Expr *userExpr = Exp->getArg(i);
2884 // Make all implicit casts explicit...ICE comes in handy:-)
2885 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2886 // Reuse the ICE type, it is exactly what the doctor ordered.
2887 QualType type = ICE->getType();
2888 if (needToScanForQualifiers(type))
2889 type = Context->getObjCIdType();
2890 // Make sure we convert "type (^)(...)" to "type (*)(...)".
2891 (void)convertBlockPointerToFunctionPointer(type);
2892 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2893 CastKind CK;
2894 if (SubExpr->getType()->isIntegralType(*Context) &&
2895 type->isBooleanType()) {
2896 CK = CK_IntegralToBoolean;
2897 } else if (type->isObjCObjectPointerType()) {
2898 if (SubExpr->getType()->isBlockPointerType()) {
2899 CK = CK_BlockPointerToObjCPointerCast;
2900 } else if (SubExpr->getType()->isPointerType()) {
2901 CK = CK_CPointerToObjCPointerCast;
2902 } else {
2903 CK = CK_BitCast;
2904 }
2905 } else {
2906 CK = CK_BitCast;
2907 }
2908
2909 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
2910 }
2911 // Make id<P...> cast into an 'id' cast.
2912 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
2913 if (CE->getType()->isObjCQualifiedIdType()) {
2914 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
2915 userExpr = CE->getSubExpr();
2916 CastKind CK;
2917 if (userExpr->getType()->isIntegralType(*Context)) {
2918 CK = CK_IntegralToPointer;
2919 } else if (userExpr->getType()->isBlockPointerType()) {
2920 CK = CK_BlockPointerToObjCPointerCast;
2921 } else if (userExpr->getType()->isPointerType()) {
2922 CK = CK_CPointerToObjCPointerCast;
2923 } else {
2924 CK = CK_BitCast;
2925 }
2926 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2927 CK, userExpr);
2928 }
2929 }
2930 MsgExprs.push_back(userExpr);
2931 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2932 // out the argument in the original expression (since we aren't deleting
2933 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
2934 //Exp->setArg(i, 0);
2935 }
2936 // Generate the funky cast.
2937 CastExpr *cast;
2938 SmallVector<QualType, 8> ArgTypes;
2939 QualType returnType;
2940
2941 // Push 'id' and 'SEL', the 2 implicit arguments.
2942 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2943 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2944 else
2945 ArgTypes.push_back(Context->getObjCIdType());
2946 ArgTypes.push_back(Context->getObjCSelType());
2947 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
2948 // Push any user argument types.
2949 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2950 E = OMD->param_end(); PI != E; ++PI) {
2951 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
2952 ? Context->getObjCIdType()
2953 : (*PI)->getType();
2954 // Make sure we convert "t (^)(...)" to "t (*)(...)".
2955 (void)convertBlockPointerToFunctionPointer(t);
2956 ArgTypes.push_back(t);
2957 }
2958 returnType = Exp->getType();
2959 convertToUnqualifiedObjCType(returnType);
2960 (void)convertBlockPointerToFunctionPointer(returnType);
2961 } else {
2962 returnType = Context->getObjCIdType();
2963 }
2964 // Get the type, we will need to reference it in a couple spots.
2965 QualType msgSendType = MsgSendFlavor->getType();
2966
2967 // Create a reference to the objc_msgSend() declaration.
2968 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
2969 VK_LValue, SourceLocation());
2970
2971 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2972 // If we don't do this cast, we get the following bizarre warning/note:
2973 // xx.m:13: warning: function called through a non-compatible type
2974 // xx.m:13: note: if this code is reached, the program will abort
2975 cast = NoTypeInfoCStyleCastExpr(Context,
2976 Context->getPointerType(Context->VoidTy),
2977 CK_BitCast, DRE);
2978
2979 // Now do the "normal" pointer to function cast.
2980 QualType castType =
2981 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2982 // If we don't have a method decl, force a variadic cast.
2983 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
2984 castType = Context->getPointerType(castType);
2985 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2986 cast);
2987
2988 // Don't forget the parens to enforce the proper binding.
2989 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2990
2991 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2992 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2993 MsgExprs.size(),
2994 FT->getResultType(), VK_RValue,
2995 EndLoc);
2996 Stmt *ReplacingStmt = CE;
2997 if (MsgSendStretFlavor) {
2998 // We have the method which returns a struct/union. Must also generate
2999 // call to objc_msgSend_stret and hang both varieties on a conditional
3000 // expression which dictate which one to envoke depending on size of
3001 // method's return type.
3002
3003 // Create a reference to the objc_msgSend_stret() declaration.
3004 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
3005 VK_LValue, SourceLocation());
3006 // Need to cast objc_msgSend_stret to "void *" (see above comment).
3007 cast = NoTypeInfoCStyleCastExpr(Context,
3008 Context->getPointerType(Context->VoidTy),
3009 CK_BitCast, STDRE);
3010 // Now do the "normal" pointer to function cast.
3011 castType = getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3012 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
3013 castType = Context->getPointerType(castType);
3014 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3015 cast);
3016
3017 // Don't forget the parens to enforce the proper binding.
3018 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
3019
3020 FT = msgSendType->getAs<FunctionType>();
3021 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
3022 MsgExprs.size(),
3023 FT->getResultType(), VK_RValue,
3024 SourceLocation());
3025
3026 // Build sizeof(returnType)
3027 UnaryExprOrTypeTraitExpr *sizeofExpr =
3028 new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
3029 Context->getTrivialTypeSourceInfo(returnType),
3030 Context->getSizeType(), SourceLocation(),
3031 SourceLocation());
3032 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3033 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3034 // For X86 it is more complicated and some kind of target specific routine
3035 // is needed to decide what to do.
3036 unsigned IntSize =
3037 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
3038 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3039 llvm::APInt(IntSize, 8),
3040 Context->IntTy,
3041 SourceLocation());
3042 BinaryOperator *lessThanExpr =
3043 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
3044 VK_RValue, OK_Ordinary, SourceLocation());
3045 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3046 ConditionalOperator *CondExpr =
3047 new (Context) ConditionalOperator(lessThanExpr,
3048 SourceLocation(), CE,
3049 SourceLocation(), STCE,
3050 returnType, VK_RValue, OK_Ordinary);
3051 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3052 CondExpr);
3053 }
3054 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3055 return ReplacingStmt;
3056}
3057
3058Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
3059 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3060 Exp->getLocEnd());
3061
3062 // Now do the actual rewrite.
3063 ReplaceStmt(Exp, ReplacingStmt);
3064
3065 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3066 return ReplacingStmt;
3067}
3068
3069// typedef struct objc_object Protocol;
3070QualType RewriteModernObjC::getProtocolType() {
3071 if (!ProtocolTypeDecl) {
3072 TypeSourceInfo *TInfo
3073 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3074 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
3075 SourceLocation(), SourceLocation(),
3076 &Context->Idents.get("Protocol"),
3077 TInfo);
3078 }
3079 return Context->getTypeDeclType(ProtocolTypeDecl);
3080}
3081
3082/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3083/// a synthesized/forward data reference (to the protocol's metadata).
3084/// The forward references (and metadata) are generated in
3085/// RewriteModernObjC::HandleTranslationUnit().
3086Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
3087 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
3088 IdentifierInfo *ID = &Context->Idents.get(Name);
3089 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
3090 SourceLocation(), ID, getProtocolType(), 0,
3091 SC_Extern, SC_None);
3092 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), VK_LValue,
3093 SourceLocation());
3094 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
3095 Context->getPointerType(DRE->getType()),
3096 VK_RValue, OK_Ordinary, SourceLocation());
3097 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
3098 CK_BitCast,
3099 DerefExpr);
3100 ReplaceStmt(Exp, castExpr);
3101 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3102 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3103 return castExpr;
3104
3105}
3106
3107bool RewriteModernObjC::BufferContainsPPDirectives(const char *startBuf,
3108 const char *endBuf) {
3109 while (startBuf < endBuf) {
3110 if (*startBuf == '#') {
3111 // Skip whitespace.
3112 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3113 ;
3114 if (!strncmp(startBuf, "if", strlen("if")) ||
3115 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3116 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3117 !strncmp(startBuf, "define", strlen("define")) ||
3118 !strncmp(startBuf, "undef", strlen("undef")) ||
3119 !strncmp(startBuf, "else", strlen("else")) ||
3120 !strncmp(startBuf, "elif", strlen("elif")) ||
3121 !strncmp(startBuf, "endif", strlen("endif")) ||
3122 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3123 !strncmp(startBuf, "include", strlen("include")) ||
3124 !strncmp(startBuf, "import", strlen("import")) ||
3125 !strncmp(startBuf, "include_next", strlen("include_next")))
3126 return true;
3127 }
3128 startBuf++;
3129 }
3130 return false;
3131}
3132
3133/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
3134/// an objective-c class with ivars.
3135void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
3136 std::string &Result) {
3137 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
3138 assert(CDecl->getName() != "" &&
3139 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003140 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003141 SmallVector<ObjCIvarDecl *, 8> IVars;
3142 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3143 IVD; IVD = IVD->getNextIvar()) {
3144 // Ignore unnamed bit-fields.
3145 if (!IVD->getDeclName())
3146 continue;
3147 IVars.push_back(IVD);
3148 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003149 SourceLocation LocStart = CDecl->getLocStart();
3150 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003151
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003152 const char *startBuf = SM->getCharacterData(LocStart);
3153 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003154
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003155 // If no ivars and no root or if its root, directly or indirectly,
3156 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003157 if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) &&
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003158 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
3159 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3160 ReplaceText(LocStart, endBuf-startBuf, Result);
3161 return;
3162 }
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003163
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003164 Result += "\nstruct ";
3165 Result += CDecl->getNameAsString();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003166 Result += "_IMPL {\n";
3167
3168 if (RCDecl) {
3169 Result += "\tstruct "; Result += RCDecl->getNameAsString();
3170 Result += "_IMPL "; Result += RCDecl->getNameAsString();
3171 Result += "_IVARS;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003172 }
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003173
3174 for (unsigned i = 0, e = IVars.size(); i < e; i++) {
3175 ObjCIvarDecl *IvarDecl = IVars[i];
3176 QualType Type = IvarDecl->getType();
3177 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
3178 Result += "\t";
3179 Result += TypeString; Result += " "; Result += IvarDecl->getNameAsString();
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00003180 if (IvarDecl->isBitField()) {
3181 Result += " : "; Result += utostr(IvarDecl->getBitWidthValue(*Context));
3182 }
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003183 Result += ";\n";
3184 }
3185 Result += "};\n";
3186 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3187 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003188}
3189
3190//===----------------------------------------------------------------------===//
3191// Meta Data Emission
3192//===----------------------------------------------------------------------===//
3193
3194
3195/// RewriteImplementations - This routine rewrites all method implementations
3196/// and emits meta-data.
3197
3198void RewriteModernObjC::RewriteImplementations() {
3199 int ClsDefCount = ClassImplementation.size();
3200 int CatDefCount = CategoryImplementation.size();
3201
3202 // Rewrite implemented methods
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00003203 for (int i = 0; i < ClsDefCount; i++) {
3204 ObjCImplementationDecl *OIMP = ClassImplementation[i];
3205 ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
3206 if (CDecl->isImplicitInterfaceDecl())
3207 assert(false &&
3208 "Legacy implicit interface rewriting not supported in moder abi");
3209 // Write struct declaration for the class matching its ivar declarations.
3210 // Note that for modern abi, this is postponed until implementation decl.
3211 // because class extensions and the implementation might declare their own
3212 // private ivars.
3213 RewriteInterfaceDecl(CDecl);
3214 RewriteImplementationDecl(OIMP);
3215 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003216
3217 for (int i = 0; i < CatDefCount; i++)
3218 RewriteImplementationDecl(CategoryImplementation[i]);
3219}
3220
3221void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
3222 const std::string &Name,
3223 ValueDecl *VD, bool def) {
3224 assert(BlockByRefDeclNo.count(VD) &&
3225 "RewriteByRefString: ByRef decl missing");
3226 if (def)
3227 ResultStr += "struct ";
3228 ResultStr += "__Block_byref_" + Name +
3229 "_" + utostr(BlockByRefDeclNo[VD]) ;
3230}
3231
3232static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
3233 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3234 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
3235 return false;
3236}
3237
3238std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3239 StringRef funcName,
3240 std::string Tag) {
3241 const FunctionType *AFT = CE->getFunctionType();
3242 QualType RT = AFT->getResultType();
3243 std::string StructRef = "struct " + Tag;
3244 std::string S = "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
3245 funcName.str() + "_" + "block_func_" + utostr(i);
3246
3247 BlockDecl *BD = CE->getBlockDecl();
3248
3249 if (isa<FunctionNoProtoType>(AFT)) {
3250 // No user-supplied arguments. Still need to pass in a pointer to the
3251 // block (to reference imported block decl refs).
3252 S += "(" + StructRef + " *__cself)";
3253 } else if (BD->param_empty()) {
3254 S += "(" + StructRef + " *__cself)";
3255 } else {
3256 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
3257 assert(FT && "SynthesizeBlockFunc: No function proto");
3258 S += '(';
3259 // first add the implicit argument.
3260 S += StructRef + " *__cself, ";
3261 std::string ParamStr;
3262 for (BlockDecl::param_iterator AI = BD->param_begin(),
3263 E = BD->param_end(); AI != E; ++AI) {
3264 if (AI != BD->param_begin()) S += ", ";
3265 ParamStr = (*AI)->getNameAsString();
3266 QualType QT = (*AI)->getType();
3267 if (convertBlockPointerToFunctionPointer(QT))
3268 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
3269 else
3270 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
3271 S += ParamStr;
3272 }
3273 if (FT->isVariadic()) {
3274 if (!BD->param_empty()) S += ", ";
3275 S += "...";
3276 }
3277 S += ')';
3278 }
3279 S += " {\n";
3280
3281 // Create local declarations to avoid rewriting all closure decl ref exprs.
3282 // First, emit a declaration for all "by ref" decls.
3283 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3284 E = BlockByRefDecls.end(); I != E; ++I) {
3285 S += " ";
3286 std::string Name = (*I)->getNameAsString();
3287 std::string TypeString;
3288 RewriteByRefString(TypeString, Name, (*I));
3289 TypeString += " *";
3290 Name = TypeString + Name;
3291 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
3292 }
3293 // Next, emit a declaration for all "by copy" declarations.
3294 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3295 E = BlockByCopyDecls.end(); I != E; ++I) {
3296 S += " ";
3297 // Handle nested closure invocation. For example:
3298 //
3299 // void (^myImportedClosure)(void);
3300 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
3301 //
3302 // void (^anotherClosure)(void);
3303 // anotherClosure = ^(void) {
3304 // myImportedClosure(); // import and invoke the closure
3305 // };
3306 //
3307 if (isTopLevelBlockPointerType((*I)->getType())) {
3308 RewriteBlockPointerTypeVariable(S, (*I));
3309 S += " = (";
3310 RewriteBlockPointerType(S, (*I)->getType());
3311 S += ")";
3312 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
3313 }
3314 else {
3315 std::string Name = (*I)->getNameAsString();
3316 QualType QT = (*I)->getType();
3317 if (HasLocalVariableExternalStorage(*I))
3318 QT = Context->getPointerType(QT);
3319 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
3320 S += Name + " = __cself->" +
3321 (*I)->getNameAsString() + "; // bound by copy\n";
3322 }
3323 }
3324 std::string RewrittenStr = RewrittenBlockExprs[CE];
3325 const char *cstr = RewrittenStr.c_str();
3326 while (*cstr++ != '{') ;
3327 S += cstr;
3328 S += "\n";
3329 return S;
3330}
3331
3332std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3333 StringRef funcName,
3334 std::string Tag) {
3335 std::string StructRef = "struct " + Tag;
3336 std::string S = "static void __";
3337
3338 S += funcName;
3339 S += "_block_copy_" + utostr(i);
3340 S += "(" + StructRef;
3341 S += "*dst, " + StructRef;
3342 S += "*src) {";
3343 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3344 E = ImportedBlockDecls.end(); I != E; ++I) {
3345 ValueDecl *VD = (*I);
3346 S += "_Block_object_assign((void*)&dst->";
3347 S += (*I)->getNameAsString();
3348 S += ", (void*)src->";
3349 S += (*I)->getNameAsString();
3350 if (BlockByRefDeclsPtrSet.count((*I)))
3351 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3352 else if (VD->getType()->isBlockPointerType())
3353 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3354 else
3355 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3356 }
3357 S += "}\n";
3358
3359 S += "\nstatic void __";
3360 S += funcName;
3361 S += "_block_dispose_" + utostr(i);
3362 S += "(" + StructRef;
3363 S += "*src) {";
3364 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3365 E = ImportedBlockDecls.end(); I != E; ++I) {
3366 ValueDecl *VD = (*I);
3367 S += "_Block_object_dispose((void*)src->";
3368 S += (*I)->getNameAsString();
3369 if (BlockByRefDeclsPtrSet.count((*I)))
3370 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3371 else if (VD->getType()->isBlockPointerType())
3372 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3373 else
3374 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3375 }
3376 S += "}\n";
3377 return S;
3378}
3379
3380std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3381 std::string Desc) {
3382 std::string S = "\nstruct " + Tag;
3383 std::string Constructor = " " + Tag;
3384
3385 S += " {\n struct __block_impl impl;\n";
3386 S += " struct " + Desc;
3387 S += "* Desc;\n";
3388
3389 Constructor += "(void *fp, "; // Invoke function pointer.
3390 Constructor += "struct " + Desc; // Descriptor pointer.
3391 Constructor += " *desc";
3392
3393 if (BlockDeclRefs.size()) {
3394 // Output all "by copy" declarations.
3395 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3396 E = BlockByCopyDecls.end(); I != E; ++I) {
3397 S += " ";
3398 std::string FieldName = (*I)->getNameAsString();
3399 std::string ArgName = "_" + FieldName;
3400 // Handle nested closure invocation. For example:
3401 //
3402 // void (^myImportedBlock)(void);
3403 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3404 //
3405 // void (^anotherBlock)(void);
3406 // anotherBlock = ^(void) {
3407 // myImportedBlock(); // import and invoke the closure
3408 // };
3409 //
3410 if (isTopLevelBlockPointerType((*I)->getType())) {
3411 S += "struct __block_impl *";
3412 Constructor += ", void *" + ArgName;
3413 } else {
3414 QualType QT = (*I)->getType();
3415 if (HasLocalVariableExternalStorage(*I))
3416 QT = Context->getPointerType(QT);
3417 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
3418 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
3419 Constructor += ", " + ArgName;
3420 }
3421 S += FieldName + ";\n";
3422 }
3423 // Output all "by ref" declarations.
3424 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3425 E = BlockByRefDecls.end(); I != E; ++I) {
3426 S += " ";
3427 std::string FieldName = (*I)->getNameAsString();
3428 std::string ArgName = "_" + FieldName;
3429 {
3430 std::string TypeString;
3431 RewriteByRefString(TypeString, FieldName, (*I));
3432 TypeString += " *";
3433 FieldName = TypeString + FieldName;
3434 ArgName = TypeString + ArgName;
3435 Constructor += ", " + ArgName;
3436 }
3437 S += FieldName + "; // by ref\n";
3438 }
3439 // Finish writing the constructor.
3440 Constructor += ", int flags=0)";
3441 // Initialize all "by copy" arguments.
3442 bool firsTime = true;
3443 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3444 E = BlockByCopyDecls.end(); I != E; ++I) {
3445 std::string Name = (*I)->getNameAsString();
3446 if (firsTime) {
3447 Constructor += " : ";
3448 firsTime = false;
3449 }
3450 else
3451 Constructor += ", ";
3452 if (isTopLevelBlockPointerType((*I)->getType()))
3453 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
3454 else
3455 Constructor += Name + "(_" + Name + ")";
3456 }
3457 // Initialize all "by ref" arguments.
3458 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3459 E = BlockByRefDecls.end(); I != E; ++I) {
3460 std::string Name = (*I)->getNameAsString();
3461 if (firsTime) {
3462 Constructor += " : ";
3463 firsTime = false;
3464 }
3465 else
3466 Constructor += ", ";
3467 Constructor += Name + "(_" + Name + "->__forwarding)";
3468 }
3469
3470 Constructor += " {\n";
3471 if (GlobalVarDecl)
3472 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3473 else
3474 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
3475 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3476
3477 Constructor += " Desc = desc;\n";
3478 } else {
3479 // Finish writing the constructor.
3480 Constructor += ", int flags=0) {\n";
3481 if (GlobalVarDecl)
3482 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3483 else
3484 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
3485 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3486 Constructor += " Desc = desc;\n";
3487 }
3488 Constructor += " ";
3489 Constructor += "}\n";
3490 S += Constructor;
3491 S += "};\n";
3492 return S;
3493}
3494
3495std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag,
3496 std::string ImplTag, int i,
3497 StringRef FunName,
3498 unsigned hasCopy) {
3499 std::string S = "\nstatic struct " + DescTag;
3500
3501 S += " {\n unsigned long reserved;\n";
3502 S += " unsigned long Block_size;\n";
3503 if (hasCopy) {
3504 S += " void (*copy)(struct ";
3505 S += ImplTag; S += "*, struct ";
3506 S += ImplTag; S += "*);\n";
3507
3508 S += " void (*dispose)(struct ";
3509 S += ImplTag; S += "*);\n";
3510 }
3511 S += "} ";
3512
3513 S += DescTag + "_DATA = { 0, sizeof(struct ";
3514 S += ImplTag + ")";
3515 if (hasCopy) {
3516 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
3517 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
3518 }
3519 S += "};\n";
3520 return S;
3521}
3522
3523void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3524 StringRef FunName) {
3525 // Insert declaration for the function in which block literal is used.
3526 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
3527 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
3528 bool RewriteSC = (GlobalVarDecl &&
3529 !Blocks.empty() &&
3530 GlobalVarDecl->getStorageClass() == SC_Static &&
3531 GlobalVarDecl->getType().getCVRQualifiers());
3532 if (RewriteSC) {
3533 std::string SC(" void __");
3534 SC += GlobalVarDecl->getNameAsString();
3535 SC += "() {}";
3536 InsertText(FunLocStart, SC);
3537 }
3538
3539 // Insert closures that were part of the function.
3540 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
3541 CollectBlockDeclRefInfo(Blocks[i]);
3542 // Need to copy-in the inner copied-in variables not actually used in this
3543 // block.
3544 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
3545 BlockDeclRefExpr *Exp = InnerDeclRefs[count++];
3546 ValueDecl *VD = Exp->getDecl();
3547 BlockDeclRefs.push_back(Exp);
3548 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
3549 BlockByCopyDeclsPtrSet.insert(VD);
3550 BlockByCopyDecls.push_back(VD);
3551 }
3552 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
3553 BlockByRefDeclsPtrSet.insert(VD);
3554 BlockByRefDecls.push_back(VD);
3555 }
3556 // imported objects in the inner blocks not used in the outer
3557 // blocks must be copied/disposed in the outer block as well.
3558 if (Exp->isByRef() ||
3559 VD->getType()->isObjCObjectPointerType() ||
3560 VD->getType()->isBlockPointerType())
3561 ImportedBlockDecls.insert(VD);
3562 }
3563
3564 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
3565 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
3566
3567 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
3568
3569 InsertText(FunLocStart, CI);
3570
3571 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
3572
3573 InsertText(FunLocStart, CF);
3574
3575 if (ImportedBlockDecls.size()) {
3576 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
3577 InsertText(FunLocStart, HF);
3578 }
3579 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
3580 ImportedBlockDecls.size() > 0);
3581 InsertText(FunLocStart, BD);
3582
3583 BlockDeclRefs.clear();
3584 BlockByRefDecls.clear();
3585 BlockByRefDeclsPtrSet.clear();
3586 BlockByCopyDecls.clear();
3587 BlockByCopyDeclsPtrSet.clear();
3588 ImportedBlockDecls.clear();
3589 }
3590 if (RewriteSC) {
3591 // Must insert any 'const/volatile/static here. Since it has been
3592 // removed as result of rewriting of block literals.
3593 std::string SC;
3594 if (GlobalVarDecl->getStorageClass() == SC_Static)
3595 SC = "static ";
3596 if (GlobalVarDecl->getType().isConstQualified())
3597 SC += "const ";
3598 if (GlobalVarDecl->getType().isVolatileQualified())
3599 SC += "volatile ";
3600 if (GlobalVarDecl->getType().isRestrictQualified())
3601 SC += "restrict ";
3602 InsertText(FunLocStart, SC);
3603 }
3604
3605 Blocks.clear();
3606 InnerDeclRefsCount.clear();
3607 InnerDeclRefs.clear();
3608 RewrittenBlockExprs.clear();
3609}
3610
3611void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3612 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
3613 StringRef FuncName = FD->getName();
3614
3615 SynthesizeBlockLiterals(FunLocStart, FuncName);
3616}
3617
3618static void BuildUniqueMethodName(std::string &Name,
3619 ObjCMethodDecl *MD) {
3620 ObjCInterfaceDecl *IFace = MD->getClassInterface();
3621 Name = IFace->getName();
3622 Name += "__" + MD->getSelector().getAsString();
3623 // Convert colons to underscores.
3624 std::string::size_type loc = 0;
3625 while ((loc = Name.find(":", loc)) != std::string::npos)
3626 Name.replace(loc, 1, "_");
3627}
3628
3629void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
3630 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3631 //SourceLocation FunLocStart = MD->getLocStart();
3632 SourceLocation FunLocStart = MD->getLocStart();
3633 std::string FuncName;
3634 BuildUniqueMethodName(FuncName, MD);
3635 SynthesizeBlockLiterals(FunLocStart, FuncName);
3636}
3637
3638void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
3639 for (Stmt::child_range CI = S->children(); CI; ++CI)
3640 if (*CI) {
3641 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3642 GetBlockDeclRefExprs(CBE->getBody());
3643 else
3644 GetBlockDeclRefExprs(*CI);
3645 }
3646 // Handle specific things.
3647 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
3648 // FIXME: Handle enums.
3649 if (!isa<FunctionDecl>(CDRE->getDecl()))
3650 BlockDeclRefs.push_back(CDRE);
3651 }
3652 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
3653 if (HasLocalVariableExternalStorage(DRE->getDecl())) {
3654 BlockDeclRefExpr *BDRE =
3655 new (Context)BlockDeclRefExpr(cast<VarDecl>(DRE->getDecl()),
3656 DRE->getType(),
3657 VK_LValue, DRE->getLocation(), false);
3658 BlockDeclRefs.push_back(BDRE);
3659 }
3660
3661 return;
3662}
3663
3664void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
3665 SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
3666 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
3667 for (Stmt::child_range CI = S->children(); CI; ++CI)
3668 if (*CI) {
3669 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
3670 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
3671 GetInnerBlockDeclRefExprs(CBE->getBody(),
3672 InnerBlockDeclRefs,
3673 InnerContexts);
3674 }
3675 else
3676 GetInnerBlockDeclRefExprs(*CI,
3677 InnerBlockDeclRefs,
3678 InnerContexts);
3679
3680 }
3681 // Handle specific things.
3682 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
3683 if (!isa<FunctionDecl>(CDRE->getDecl()) &&
3684 !InnerContexts.count(CDRE->getDecl()->getDeclContext()))
3685 InnerBlockDeclRefs.push_back(CDRE);
3686 }
3687 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
3688 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
3689 if (Var->isFunctionOrMethodVarDecl())
3690 ImportedLocalExternalDecls.insert(Var);
3691 }
3692
3693 return;
3694}
3695
3696/// convertFunctionTypeOfBlocks - This routine converts a function type
3697/// whose result type may be a block pointer or whose argument type(s)
3698/// might be block pointers to an equivalent function type replacing
3699/// all block pointers to function pointers.
3700QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
3701 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
3702 // FTP will be null for closures that don't take arguments.
3703 // Generate a funky cast.
3704 SmallVector<QualType, 8> ArgTypes;
3705 QualType Res = FT->getResultType();
3706 bool HasBlockType = convertBlockPointerToFunctionPointer(Res);
3707
3708 if (FTP) {
3709 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
3710 E = FTP->arg_type_end(); I && (I != E); ++I) {
3711 QualType t = *I;
3712 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3713 if (convertBlockPointerToFunctionPointer(t))
3714 HasBlockType = true;
3715 ArgTypes.push_back(t);
3716 }
3717 }
3718 QualType FuncType;
3719 // FIXME. Does this work if block takes no argument but has a return type
3720 // which is of block type?
3721 if (HasBlockType)
3722 FuncType = getSimpleFunctionType(Res, &ArgTypes[0], ArgTypes.size());
3723 else FuncType = QualType(FT, 0);
3724 return FuncType;
3725}
3726
3727Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
3728 // Navigate to relevant type information.
3729 const BlockPointerType *CPT = 0;
3730
3731 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
3732 CPT = DRE->getType()->getAs<BlockPointerType>();
3733 } else if (const BlockDeclRefExpr *CDRE =
3734 dyn_cast<BlockDeclRefExpr>(BlockExp)) {
3735 CPT = CDRE->getType()->getAs<BlockPointerType>();
3736 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
3737 CPT = MExpr->getType()->getAs<BlockPointerType>();
3738 }
3739 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
3740 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
3741 }
3742 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
3743 CPT = IEXPR->getType()->getAs<BlockPointerType>();
3744 else if (const ConditionalOperator *CEXPR =
3745 dyn_cast<ConditionalOperator>(BlockExp)) {
3746 Expr *LHSExp = CEXPR->getLHS();
3747 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
3748 Expr *RHSExp = CEXPR->getRHS();
3749 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
3750 Expr *CONDExp = CEXPR->getCond();
3751 ConditionalOperator *CondExpr =
3752 new (Context) ConditionalOperator(CONDExp,
3753 SourceLocation(), cast<Expr>(LHSStmt),
3754 SourceLocation(), cast<Expr>(RHSStmt),
3755 Exp->getType(), VK_RValue, OK_Ordinary);
3756 return CondExpr;
3757 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
3758 CPT = IRE->getType()->getAs<BlockPointerType>();
3759 } else if (const PseudoObjectExpr *POE
3760 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
3761 CPT = POE->getType()->castAs<BlockPointerType>();
3762 } else {
3763 assert(1 && "RewriteBlockClass: Bad type");
3764 }
3765 assert(CPT && "RewriteBlockClass: Bad type");
3766 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
3767 assert(FT && "RewriteBlockClass: Bad type");
3768 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
3769 // FTP will be null for closures that don't take arguments.
3770
3771 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3772 SourceLocation(), SourceLocation(),
3773 &Context->Idents.get("__block_impl"));
3774 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
3775
3776 // Generate a funky cast.
3777 SmallVector<QualType, 8> ArgTypes;
3778
3779 // Push the block argument type.
3780 ArgTypes.push_back(PtrBlock);
3781 if (FTP) {
3782 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
3783 E = FTP->arg_type_end(); I && (I != E); ++I) {
3784 QualType t = *I;
3785 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3786 if (!convertBlockPointerToFunctionPointer(t))
3787 convertToUnqualifiedObjCType(t);
3788 ArgTypes.push_back(t);
3789 }
3790 }
3791 // Now do the pointer to function cast.
3792 QualType PtrToFuncCastType
3793 = getSimpleFunctionType(Exp->getType(), &ArgTypes[0], ArgTypes.size());
3794
3795 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
3796
3797 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
3798 CK_BitCast,
3799 const_cast<Expr*>(BlockExp));
3800 // Don't forget the parens to enforce the proper binding.
3801 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3802 BlkCast);
3803 //PE->dump();
3804
3805 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
3806 SourceLocation(),
3807 &Context->Idents.get("FuncPtr"),
3808 Context->VoidPtrTy, 0,
3809 /*BitWidth=*/0, /*Mutable=*/true,
3810 /*HasInit=*/false);
3811 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
3812 FD->getType(), VK_LValue,
3813 OK_Ordinary);
3814
3815
3816 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
3817 CK_BitCast, ME);
3818 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
3819
3820 SmallVector<Expr*, 8> BlkExprs;
3821 // Add the implicit argument.
3822 BlkExprs.push_back(BlkCast);
3823 // Add the user arguments.
3824 for (CallExpr::arg_iterator I = Exp->arg_begin(),
3825 E = Exp->arg_end(); I != E; ++I) {
3826 BlkExprs.push_back(*I);
3827 }
3828 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
3829 BlkExprs.size(),
3830 Exp->getType(), VK_RValue,
3831 SourceLocation());
3832 return CE;
3833}
3834
3835// We need to return the rewritten expression to handle cases where the
3836// BlockDeclRefExpr is embedded in another expression being rewritten.
3837// For example:
3838//
3839// int main() {
3840// __block Foo *f;
3841// __block int i;
3842//
3843// void (^myblock)() = ^() {
3844// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
3845// i = 77;
3846// };
3847//}
3848Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(Expr *DeclRefExp) {
3849 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
3850 // for each DeclRefExp where BYREFVAR is name of the variable.
3851 ValueDecl *VD;
3852 bool isArrow = true;
3853 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(DeclRefExp))
3854 VD = BDRE->getDecl();
3855 else {
3856 VD = cast<DeclRefExpr>(DeclRefExp)->getDecl();
3857 isArrow = false;
3858 }
3859
3860 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
3861 SourceLocation(),
3862 &Context->Idents.get("__forwarding"),
3863 Context->VoidPtrTy, 0,
3864 /*BitWidth=*/0, /*Mutable=*/true,
3865 /*HasInit=*/false);
3866 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
3867 FD, SourceLocation(),
3868 FD->getType(), VK_LValue,
3869 OK_Ordinary);
3870
3871 StringRef Name = VD->getName();
3872 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
3873 &Context->Idents.get(Name),
3874 Context->VoidPtrTy, 0,
3875 /*BitWidth=*/0, /*Mutable=*/true,
3876 /*HasInit=*/false);
3877 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
3878 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
3879
3880
3881
3882 // Need parens to enforce precedence.
3883 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
3884 DeclRefExp->getExprLoc(),
3885 ME);
3886 ReplaceStmt(DeclRefExp, PE);
3887 return PE;
3888}
3889
3890// Rewrites the imported local variable V with external storage
3891// (static, extern, etc.) as *V
3892//
3893Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
3894 ValueDecl *VD = DRE->getDecl();
3895 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3896 if (!ImportedLocalExternalDecls.count(Var))
3897 return DRE;
3898 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
3899 VK_LValue, OK_Ordinary,
3900 DRE->getLocation());
3901 // Need parens to enforce precedence.
3902 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3903 Exp);
3904 ReplaceStmt(DRE, PE);
3905 return PE;
3906}
3907
3908void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
3909 SourceLocation LocStart = CE->getLParenLoc();
3910 SourceLocation LocEnd = CE->getRParenLoc();
3911
3912 // Need to avoid trying to rewrite synthesized casts.
3913 if (LocStart.isInvalid())
3914 return;
3915 // Need to avoid trying to rewrite casts contained in macros.
3916 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
3917 return;
3918
3919 const char *startBuf = SM->getCharacterData(LocStart);
3920 const char *endBuf = SM->getCharacterData(LocEnd);
3921 QualType QT = CE->getType();
3922 const Type* TypePtr = QT->getAs<Type>();
3923 if (isa<TypeOfExprType>(TypePtr)) {
3924 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
3925 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
3926 std::string TypeAsString = "(";
3927 RewriteBlockPointerType(TypeAsString, QT);
3928 TypeAsString += ")";
3929 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
3930 return;
3931 }
3932 // advance the location to startArgList.
3933 const char *argPtr = startBuf;
3934
3935 while (*argPtr++ && (argPtr < endBuf)) {
3936 switch (*argPtr) {
3937 case '^':
3938 // Replace the '^' with '*'.
3939 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
3940 ReplaceText(LocStart, 1, "*");
3941 break;
3942 }
3943 }
3944 return;
3945}
3946
3947void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
3948 SourceLocation DeclLoc = FD->getLocation();
3949 unsigned parenCount = 0;
3950
3951 // We have 1 or more arguments that have closure pointers.
3952 const char *startBuf = SM->getCharacterData(DeclLoc);
3953 const char *startArgList = strchr(startBuf, '(');
3954
3955 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
3956
3957 parenCount++;
3958 // advance the location to startArgList.
3959 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
3960 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
3961
3962 const char *argPtr = startArgList;
3963
3964 while (*argPtr++ && parenCount) {
3965 switch (*argPtr) {
3966 case '^':
3967 // Replace the '^' with '*'.
3968 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
3969 ReplaceText(DeclLoc, 1, "*");
3970 break;
3971 case '(':
3972 parenCount++;
3973 break;
3974 case ')':
3975 parenCount--;
3976 break;
3977 }
3978 }
3979 return;
3980}
3981
3982bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
3983 const FunctionProtoType *FTP;
3984 const PointerType *PT = QT->getAs<PointerType>();
3985 if (PT) {
3986 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
3987 } else {
3988 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
3989 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
3990 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
3991 }
3992 if (FTP) {
3993 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
3994 E = FTP->arg_type_end(); I != E; ++I)
3995 if (isTopLevelBlockPointerType(*I))
3996 return true;
3997 }
3998 return false;
3999}
4000
4001bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4002 const FunctionProtoType *FTP;
4003 const PointerType *PT = QT->getAs<PointerType>();
4004 if (PT) {
4005 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4006 } else {
4007 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4008 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4009 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4010 }
4011 if (FTP) {
4012 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4013 E = FTP->arg_type_end(); I != E; ++I) {
4014 if ((*I)->isObjCQualifiedIdType())
4015 return true;
4016 if ((*I)->isObjCObjectPointerType() &&
4017 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
4018 return true;
4019 }
4020
4021 }
4022 return false;
4023}
4024
4025void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4026 const char *&RParen) {
4027 const char *argPtr = strchr(Name, '(');
4028 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
4029
4030 LParen = argPtr; // output the start.
4031 argPtr++; // skip past the left paren.
4032 unsigned parenCount = 1;
4033
4034 while (*argPtr && parenCount) {
4035 switch (*argPtr) {
4036 case '(': parenCount++; break;
4037 case ')': parenCount--; break;
4038 default: break;
4039 }
4040 if (parenCount) argPtr++;
4041 }
4042 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4043 RParen = argPtr; // output the end
4044}
4045
4046void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4047 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4048 RewriteBlockPointerFunctionArgs(FD);
4049 return;
4050 }
4051 // Handle Variables and Typedefs.
4052 SourceLocation DeclLoc = ND->getLocation();
4053 QualType DeclT;
4054 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4055 DeclT = VD->getType();
4056 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
4057 DeclT = TDD->getUnderlyingType();
4058 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4059 DeclT = FD->getType();
4060 else
4061 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
4062
4063 const char *startBuf = SM->getCharacterData(DeclLoc);
4064 const char *endBuf = startBuf;
4065 // scan backward (from the decl location) for the end of the previous decl.
4066 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4067 startBuf--;
4068 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
4069 std::string buf;
4070 unsigned OrigLength=0;
4071 // *startBuf != '^' if we are dealing with a pointer to function that
4072 // may take block argument types (which will be handled below).
4073 if (*startBuf == '^') {
4074 // Replace the '^' with '*', computing a negative offset.
4075 buf = '*';
4076 startBuf++;
4077 OrigLength++;
4078 }
4079 while (*startBuf != ')') {
4080 buf += *startBuf;
4081 startBuf++;
4082 OrigLength++;
4083 }
4084 buf += ')';
4085 OrigLength++;
4086
4087 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4088 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
4089 // Replace the '^' with '*' for arguments.
4090 // Replace id<P> with id/*<>*/
4091 DeclLoc = ND->getLocation();
4092 startBuf = SM->getCharacterData(DeclLoc);
4093 const char *argListBegin, *argListEnd;
4094 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4095 while (argListBegin < argListEnd) {
4096 if (*argListBegin == '^')
4097 buf += '*';
4098 else if (*argListBegin == '<') {
4099 buf += "/*";
4100 buf += *argListBegin++;
4101 OrigLength++;;
4102 while (*argListBegin != '>') {
4103 buf += *argListBegin++;
4104 OrigLength++;
4105 }
4106 buf += *argListBegin;
4107 buf += "*/";
4108 }
4109 else
4110 buf += *argListBegin;
4111 argListBegin++;
4112 OrigLength++;
4113 }
4114 buf += ')';
4115 OrigLength++;
4116 }
4117 ReplaceText(Start, OrigLength, buf);
4118
4119 return;
4120}
4121
4122
4123/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4124/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4125/// struct Block_byref_id_object *src) {
4126/// _Block_object_assign (&_dest->object, _src->object,
4127/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4128/// [|BLOCK_FIELD_IS_WEAK]) // object
4129/// _Block_object_assign(&_dest->object, _src->object,
4130/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4131/// [|BLOCK_FIELD_IS_WEAK]) // block
4132/// }
4133/// And:
4134/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4135/// _Block_object_dispose(_src->object,
4136/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4137/// [|BLOCK_FIELD_IS_WEAK]) // object
4138/// _Block_object_dispose(_src->object,
4139/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4140/// [|BLOCK_FIELD_IS_WEAK]) // block
4141/// }
4142
4143std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4144 int flag) {
4145 std::string S;
4146 if (CopyDestroyCache.count(flag))
4147 return S;
4148 CopyDestroyCache.insert(flag);
4149 S = "static void __Block_byref_id_object_copy_";
4150 S += utostr(flag);
4151 S += "(void *dst, void *src) {\n";
4152
4153 // offset into the object pointer is computed as:
4154 // void * + void* + int + int + void* + void *
4155 unsigned IntSize =
4156 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4157 unsigned VoidPtrSize =
4158 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4159
4160 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
4161 S += " _Block_object_assign((char*)dst + ";
4162 S += utostr(offset);
4163 S += ", *(void * *) ((char*)src + ";
4164 S += utostr(offset);
4165 S += "), ";
4166 S += utostr(flag);
4167 S += ");\n}\n";
4168
4169 S += "static void __Block_byref_id_object_dispose_";
4170 S += utostr(flag);
4171 S += "(void *src) {\n";
4172 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4173 S += utostr(offset);
4174 S += "), ";
4175 S += utostr(flag);
4176 S += ");\n}\n";
4177 return S;
4178}
4179
4180/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4181/// the declaration into:
4182/// struct __Block_byref_ND {
4183/// void *__isa; // NULL for everything except __weak pointers
4184/// struct __Block_byref_ND *__forwarding;
4185/// int32_t __flags;
4186/// int32_t __size;
4187/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4188/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
4189/// typex ND;
4190/// };
4191///
4192/// It then replaces declaration of ND variable with:
4193/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4194/// __size=sizeof(struct __Block_byref_ND),
4195/// ND=initializer-if-any};
4196///
4197///
4198void RewriteModernObjC::RewriteByRefVar(VarDecl *ND) {
4199 // Insert declaration for the function in which block literal is
4200 // used.
4201 if (CurFunctionDeclToDeclareForBlock)
4202 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
4203 int flag = 0;
4204 int isa = 0;
4205 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
4206 if (DeclLoc.isInvalid())
4207 // If type location is missing, it is because of missing type (a warning).
4208 // Use variable's location which is good for this case.
4209 DeclLoc = ND->getLocation();
4210 const char *startBuf = SM->getCharacterData(DeclLoc);
4211 SourceLocation X = ND->getLocEnd();
4212 X = SM->getExpansionLoc(X);
4213 const char *endBuf = SM->getCharacterData(X);
4214 std::string Name(ND->getNameAsString());
4215 std::string ByrefType;
4216 RewriteByRefString(ByrefType, Name, ND, true);
4217 ByrefType += " {\n";
4218 ByrefType += " void *__isa;\n";
4219 RewriteByRefString(ByrefType, Name, ND);
4220 ByrefType += " *__forwarding;\n";
4221 ByrefType += " int __flags;\n";
4222 ByrefType += " int __size;\n";
4223 // Add void *__Block_byref_id_object_copy;
4224 // void *__Block_byref_id_object_dispose; if needed.
4225 QualType Ty = ND->getType();
4226 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
4227 if (HasCopyAndDispose) {
4228 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4229 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
4230 }
4231
4232 QualType T = Ty;
4233 (void)convertBlockPointerToFunctionPointer(T);
4234 T.getAsStringInternal(Name, Context->getPrintingPolicy());
4235
4236 ByrefType += " " + Name + ";\n";
4237 ByrefType += "};\n";
4238 // Insert this type in global scope. It is needed by helper function.
4239 SourceLocation FunLocStart;
4240 if (CurFunctionDef)
4241 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4242 else {
4243 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4244 FunLocStart = CurMethodDef->getLocStart();
4245 }
4246 InsertText(FunLocStart, ByrefType);
4247 if (Ty.isObjCGCWeak()) {
4248 flag |= BLOCK_FIELD_IS_WEAK;
4249 isa = 1;
4250 }
4251
4252 if (HasCopyAndDispose) {
4253 flag = BLOCK_BYREF_CALLER;
4254 QualType Ty = ND->getType();
4255 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4256 if (Ty->isBlockPointerType())
4257 flag |= BLOCK_FIELD_IS_BLOCK;
4258 else
4259 flag |= BLOCK_FIELD_IS_OBJECT;
4260 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
4261 if (!HF.empty())
4262 InsertText(FunLocStart, HF);
4263 }
4264
4265 // struct __Block_byref_ND ND =
4266 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4267 // initializer-if-any};
4268 bool hasInit = (ND->getInit() != 0);
4269 unsigned flags = 0;
4270 if (HasCopyAndDispose)
4271 flags |= BLOCK_HAS_COPY_DISPOSE;
4272 Name = ND->getNameAsString();
4273 ByrefType.clear();
4274 RewriteByRefString(ByrefType, Name, ND);
4275 std::string ForwardingCastType("(");
4276 ForwardingCastType += ByrefType + " *)";
4277 if (!hasInit) {
4278 ByrefType += " " + Name + " = {(void*)";
4279 ByrefType += utostr(isa);
4280 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
4281 ByrefType += utostr(flags);
4282 ByrefType += ", ";
4283 ByrefType += "sizeof(";
4284 RewriteByRefString(ByrefType, Name, ND);
4285 ByrefType += ")";
4286 if (HasCopyAndDispose) {
4287 ByrefType += ", __Block_byref_id_object_copy_";
4288 ByrefType += utostr(flag);
4289 ByrefType += ", __Block_byref_id_object_dispose_";
4290 ByrefType += utostr(flag);
4291 }
4292 ByrefType += "};\n";
4293 unsigned nameSize = Name.size();
4294 // for block or function pointer declaration. Name is aleady
4295 // part of the declaration.
4296 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
4297 nameSize = 1;
4298 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
4299 }
4300 else {
4301 SourceLocation startLoc;
4302 Expr *E = ND->getInit();
4303 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
4304 startLoc = ECE->getLParenLoc();
4305 else
4306 startLoc = E->getLocStart();
4307 startLoc = SM->getExpansionLoc(startLoc);
4308 endBuf = SM->getCharacterData(startLoc);
4309 ByrefType += " " + Name;
4310 ByrefType += " = {(void*)";
4311 ByrefType += utostr(isa);
4312 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
4313 ByrefType += utostr(flags);
4314 ByrefType += ", ";
4315 ByrefType += "sizeof(";
4316 RewriteByRefString(ByrefType, Name, ND);
4317 ByrefType += "), ";
4318 if (HasCopyAndDispose) {
4319 ByrefType += "__Block_byref_id_object_copy_";
4320 ByrefType += utostr(flag);
4321 ByrefType += ", __Block_byref_id_object_dispose_";
4322 ByrefType += utostr(flag);
4323 ByrefType += ", ";
4324 }
4325 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
4326
4327 // Complete the newly synthesized compound expression by inserting a right
4328 // curly brace before the end of the declaration.
4329 // FIXME: This approach avoids rewriting the initializer expression. It
4330 // also assumes there is only one declarator. For example, the following
4331 // isn't currently supported by this routine (in general):
4332 //
4333 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4334 //
4335 const char *startInitializerBuf = SM->getCharacterData(startLoc);
4336 const char *semiBuf = strchr(startInitializerBuf, ';');
4337 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4338 SourceLocation semiLoc =
4339 startLoc.getLocWithOffset(semiBuf-startInitializerBuf);
4340
4341 InsertText(semiLoc, "}");
4342 }
4343 return;
4344}
4345
4346void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
4347 // Add initializers for any closure decl refs.
4348 GetBlockDeclRefExprs(Exp->getBody());
4349 if (BlockDeclRefs.size()) {
4350 // Unique all "by copy" declarations.
4351 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4352 if (!BlockDeclRefs[i]->isByRef()) {
4353 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4354 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4355 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
4356 }
4357 }
4358 // Unique all "by ref" declarations.
4359 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4360 if (BlockDeclRefs[i]->isByRef()) {
4361 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4362 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4363 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
4364 }
4365 }
4366 // Find any imported blocks...they will need special attention.
4367 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4368 if (BlockDeclRefs[i]->isByRef() ||
4369 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4370 BlockDeclRefs[i]->getType()->isBlockPointerType())
4371 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4372 }
4373}
4374
4375FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) {
4376 IdentifierInfo *ID = &Context->Idents.get(name);
4377 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
4378 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
4379 SourceLocation(), ID, FType, 0, SC_Extern,
4380 SC_None, false, false);
4381}
4382
4383Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp,
4384 const SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs) {
4385 const BlockDecl *block = Exp->getBlockDecl();
4386 Blocks.push_back(Exp);
4387
4388 CollectBlockDeclRefInfo(Exp);
4389
4390 // Add inner imported variables now used in current block.
4391 int countOfInnerDecls = 0;
4392 if (!InnerBlockDeclRefs.empty()) {
4393 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
4394 BlockDeclRefExpr *Exp = InnerBlockDeclRefs[i];
4395 ValueDecl *VD = Exp->getDecl();
4396 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
4397 // We need to save the copied-in variables in nested
4398 // blocks because it is needed at the end for some of the API generations.
4399 // See SynthesizeBlockLiterals routine.
4400 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4401 BlockDeclRefs.push_back(Exp);
4402 BlockByCopyDeclsPtrSet.insert(VD);
4403 BlockByCopyDecls.push_back(VD);
4404 }
4405 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
4406 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4407 BlockDeclRefs.push_back(Exp);
4408 BlockByRefDeclsPtrSet.insert(VD);
4409 BlockByRefDecls.push_back(VD);
4410 }
4411 }
4412 // Find any imported blocks...they will need special attention.
4413 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
4414 if (InnerBlockDeclRefs[i]->isByRef() ||
4415 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4416 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
4417 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
4418 }
4419 InnerDeclRefsCount.push_back(countOfInnerDecls);
4420
4421 std::string FuncName;
4422
4423 if (CurFunctionDef)
4424 FuncName = CurFunctionDef->getNameAsString();
4425 else if (CurMethodDef)
4426 BuildUniqueMethodName(FuncName, CurMethodDef);
4427 else if (GlobalVarDecl)
4428 FuncName = std::string(GlobalVarDecl->getNameAsString());
4429
4430 std::string BlockNumber = utostr(Blocks.size()-1);
4431
4432 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4433 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
4434
4435 // Get a pointer to the function type so we can cast appropriately.
4436 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
4437 QualType FType = Context->getPointerType(BFT);
4438
4439 FunctionDecl *FD;
4440 Expr *NewRep;
4441
4442 // Simulate a contructor call...
4443 FD = SynthBlockInitFunctionDecl(Tag);
4444 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, VK_RValue,
4445 SourceLocation());
4446
4447 SmallVector<Expr*, 4> InitExprs;
4448
4449 // Initialize the block function.
4450 FD = SynthBlockInitFunctionDecl(Func);
4451 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
4452 SourceLocation());
4453 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
4454 CK_BitCast, Arg);
4455 InitExprs.push_back(castExpr);
4456
4457 // Initialize the block descriptor.
4458 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
4459
4460 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
4461 SourceLocation(), SourceLocation(),
4462 &Context->Idents.get(DescData.c_str()),
4463 Context->VoidPtrTy, 0,
4464 SC_Static, SC_None);
4465 UnaryOperator *DescRefExpr =
4466 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD,
4467 Context->VoidPtrTy,
4468 VK_LValue,
4469 SourceLocation()),
4470 UO_AddrOf,
4471 Context->getPointerType(Context->VoidPtrTy),
4472 VK_RValue, OK_Ordinary,
4473 SourceLocation());
4474 InitExprs.push_back(DescRefExpr);
4475
4476 // Add initializers for any closure decl refs.
4477 if (BlockDeclRefs.size()) {
4478 Expr *Exp;
4479 // Output all "by copy" declarations.
4480 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4481 E = BlockByCopyDecls.end(); I != E; ++I) {
4482 if (isObjCType((*I)->getType())) {
4483 // FIXME: Conform to ABI ([[obj retain] autorelease]).
4484 FD = SynthBlockInitFunctionDecl((*I)->getName());
4485 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
4486 SourceLocation());
4487 if (HasLocalVariableExternalStorage(*I)) {
4488 QualType QT = (*I)->getType();
4489 QT = Context->getPointerType(QT);
4490 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4491 OK_Ordinary, SourceLocation());
4492 }
4493 } else if (isTopLevelBlockPointerType((*I)->getType())) {
4494 FD = SynthBlockInitFunctionDecl((*I)->getName());
4495 Arg = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
4496 SourceLocation());
4497 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
4498 CK_BitCast, Arg);
4499 } else {
4500 FD = SynthBlockInitFunctionDecl((*I)->getName());
4501 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
4502 SourceLocation());
4503 if (HasLocalVariableExternalStorage(*I)) {
4504 QualType QT = (*I)->getType();
4505 QT = Context->getPointerType(QT);
4506 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4507 OK_Ordinary, SourceLocation());
4508 }
4509
4510 }
4511 InitExprs.push_back(Exp);
4512 }
4513 // Output all "by ref" declarations.
4514 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4515 E = BlockByRefDecls.end(); I != E; ++I) {
4516 ValueDecl *ND = (*I);
4517 std::string Name(ND->getNameAsString());
4518 std::string RecName;
4519 RewriteByRefString(RecName, Name, ND, true);
4520 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
4521 + sizeof("struct"));
4522 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4523 SourceLocation(), SourceLocation(),
4524 II);
4525 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
4526 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
4527
4528 FD = SynthBlockInitFunctionDecl((*I)->getName());
4529 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
4530 SourceLocation());
4531 bool isNestedCapturedVar = false;
4532 if (block)
4533 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
4534 ce = block->capture_end(); ci != ce; ++ci) {
4535 const VarDecl *variable = ci->getVariable();
4536 if (variable == ND && ci->isNested()) {
4537 assert (ci->isByRef() &&
4538 "SynthBlockInitExpr - captured block variable is not byref");
4539 isNestedCapturedVar = true;
4540 break;
4541 }
4542 }
4543 // captured nested byref variable has its address passed. Do not take
4544 // its address again.
4545 if (!isNestedCapturedVar)
4546 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
4547 Context->getPointerType(Exp->getType()),
4548 VK_RValue, OK_Ordinary, SourceLocation());
4549 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
4550 InitExprs.push_back(Exp);
4551 }
4552 }
4553 if (ImportedBlockDecls.size()) {
4554 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
4555 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
4556 unsigned IntSize =
4557 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4558 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
4559 Context->IntTy, SourceLocation());
4560 InitExprs.push_back(FlagExp);
4561 }
4562 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
4563 FType, VK_LValue, SourceLocation());
4564 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
4565 Context->getPointerType(NewRep->getType()),
4566 VK_RValue, OK_Ordinary, SourceLocation());
4567 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
4568 NewRep);
4569 BlockDeclRefs.clear();
4570 BlockByRefDecls.clear();
4571 BlockByRefDeclsPtrSet.clear();
4572 BlockByCopyDecls.clear();
4573 BlockByCopyDeclsPtrSet.clear();
4574 ImportedBlockDecls.clear();
4575 return NewRep;
4576}
4577
4578bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
4579 if (const ObjCForCollectionStmt * CS =
4580 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
4581 return CS->getElement() == DS;
4582 return false;
4583}
4584
4585//===----------------------------------------------------------------------===//
4586// Function Body / Expression rewriting
4587//===----------------------------------------------------------------------===//
4588
4589Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
4590 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4591 isa<DoStmt>(S) || isa<ForStmt>(S))
4592 Stmts.push_back(S);
4593 else if (isa<ObjCForCollectionStmt>(S)) {
4594 Stmts.push_back(S);
4595 ObjCBcLabelNo.push_back(++BcLabelCount);
4596 }
4597
4598 // Pseudo-object operations and ivar references need special
4599 // treatment because we're going to recursively rewrite them.
4600 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
4601 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
4602 return RewritePropertyOrImplicitSetter(PseudoOp);
4603 } else {
4604 return RewritePropertyOrImplicitGetter(PseudoOp);
4605 }
4606 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
4607 return RewriteObjCIvarRefExpr(IvarRefExpr);
4608 }
4609
4610 SourceRange OrigStmtRange = S->getSourceRange();
4611
4612 // Perform a bottom up rewrite of all children.
4613 for (Stmt::child_range CI = S->children(); CI; ++CI)
4614 if (*CI) {
4615 Stmt *childStmt = (*CI);
4616 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
4617 if (newStmt) {
4618 *CI = newStmt;
4619 }
4620 }
4621
4622 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
4623 SmallVector<BlockDeclRefExpr *, 8> InnerBlockDeclRefs;
4624 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
4625 InnerContexts.insert(BE->getBlockDecl());
4626 ImportedLocalExternalDecls.clear();
4627 GetInnerBlockDeclRefExprs(BE->getBody(),
4628 InnerBlockDeclRefs, InnerContexts);
4629 // Rewrite the block body in place.
4630 Stmt *SaveCurrentBody = CurrentBody;
4631 CurrentBody = BE->getBody();
4632 PropParentMap = 0;
4633 // block literal on rhs of a property-dot-sytax assignment
4634 // must be replaced by its synthesize ast so getRewrittenText
4635 // works as expected. In this case, what actually ends up on RHS
4636 // is the blockTranscribed which is the helper function for the
4637 // block literal; as in: self.c = ^() {[ace ARR];};
4638 bool saveDisableReplaceStmt = DisableReplaceStmt;
4639 DisableReplaceStmt = false;
4640 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
4641 DisableReplaceStmt = saveDisableReplaceStmt;
4642 CurrentBody = SaveCurrentBody;
4643 PropParentMap = 0;
4644 ImportedLocalExternalDecls.clear();
4645 // Now we snarf the rewritten text and stash it away for later use.
4646 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
4647 RewrittenBlockExprs[BE] = Str;
4648
4649 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
4650
4651 //blockTranscribed->dump();
4652 ReplaceStmt(S, blockTranscribed);
4653 return blockTranscribed;
4654 }
4655 // Handle specific things.
4656 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4657 return RewriteAtEncode(AtEncode);
4658
4659 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4660 return RewriteAtSelector(AtSelector);
4661
4662 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4663 return RewriteObjCStringLiteral(AtString);
4664
4665 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
4666#if 0
4667 // Before we rewrite it, put the original message expression in a comment.
4668 SourceLocation startLoc = MessExpr->getLocStart();
4669 SourceLocation endLoc = MessExpr->getLocEnd();
4670
4671 const char *startBuf = SM->getCharacterData(startLoc);
4672 const char *endBuf = SM->getCharacterData(endLoc);
4673
4674 std::string messString;
4675 messString += "// ";
4676 messString.append(startBuf, endBuf-startBuf+1);
4677 messString += "\n";
4678
4679 // FIXME: Missing definition of
4680 // InsertText(clang::SourceLocation, char const*, unsigned int).
4681 // InsertText(startLoc, messString.c_str(), messString.size());
4682 // Tried this, but it didn't work either...
4683 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
4684#endif
4685 return RewriteMessageExpr(MessExpr);
4686 }
4687
4688 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4689 return RewriteObjCTryStmt(StmtTry);
4690
4691 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4692 return RewriteObjCSynchronizedStmt(StmtTry);
4693
4694 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4695 return RewriteObjCThrowStmt(StmtThrow);
4696
4697 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4698 return RewriteObjCProtocolExpr(ProtocolExp);
4699
4700 if (ObjCForCollectionStmt *StmtForCollection =
4701 dyn_cast<ObjCForCollectionStmt>(S))
4702 return RewriteObjCForCollectionStmt(StmtForCollection,
4703 OrigStmtRange.getEnd());
4704 if (BreakStmt *StmtBreakStmt =
4705 dyn_cast<BreakStmt>(S))
4706 return RewriteBreakStmt(StmtBreakStmt);
4707 if (ContinueStmt *StmtContinueStmt =
4708 dyn_cast<ContinueStmt>(S))
4709 return RewriteContinueStmt(StmtContinueStmt);
4710
4711 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
4712 // and cast exprs.
4713 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4714 // FIXME: What we're doing here is modifying the type-specifier that
4715 // precedes the first Decl. In the future the DeclGroup should have
4716 // a separate type-specifier that we can rewrite.
4717 // NOTE: We need to avoid rewriting the DeclStmt if it is within
4718 // the context of an ObjCForCollectionStmt. For example:
4719 // NSArray *someArray;
4720 // for (id <FooProtocol> index in someArray) ;
4721 // This is because RewriteObjCForCollectionStmt() does textual rewriting
4722 // and it depends on the original text locations/positions.
4723 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
4724 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
4725
4726 // Blocks rewrite rules.
4727 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
4728 DI != DE; ++DI) {
4729 Decl *SD = *DI;
4730 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
4731 if (isTopLevelBlockPointerType(ND->getType()))
4732 RewriteBlockPointerDecl(ND);
4733 else if (ND->getType()->isFunctionPointerType())
4734 CheckFunctionPointerDecl(ND->getType(), ND);
4735 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
4736 if (VD->hasAttr<BlocksAttr>()) {
4737 static unsigned uniqueByrefDeclCount = 0;
4738 assert(!BlockByRefDeclNo.count(ND) &&
4739 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
4740 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
4741 RewriteByRefVar(VD);
4742 }
4743 else
4744 RewriteTypeOfDecl(VD);
4745 }
4746 }
4747 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
4748 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
4749 RewriteBlockPointerDecl(TD);
4750 else if (TD->getUnderlyingType()->isFunctionPointerType())
4751 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4752 }
4753 }
4754 }
4755
4756 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4757 RewriteObjCQualifiedInterfaceTypes(CE);
4758
4759 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4760 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4761 assert(!Stmts.empty() && "Statement stack is empty");
4762 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4763 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
4764 && "Statement stack mismatch");
4765 Stmts.pop_back();
4766 }
4767 // Handle blocks rewriting.
4768 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
4769 if (BDRE->isByRef())
4770 return RewriteBlockDeclRefExpr(BDRE);
4771 }
4772 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4773 ValueDecl *VD = DRE->getDecl();
4774 if (VD->hasAttr<BlocksAttr>())
4775 return RewriteBlockDeclRefExpr(DRE);
4776 if (HasLocalVariableExternalStorage(VD))
4777 return RewriteLocalVariableExternalStorage(DRE);
4778 }
4779
4780 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
4781 if (CE->getCallee()->getType()->isBlockPointerType()) {
4782 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
4783 ReplaceStmt(S, BlockCall);
4784 return BlockCall;
4785 }
4786 }
4787 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
4788 RewriteCastExpr(CE);
4789 }
4790#if 0
4791 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
4792 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
4793 ICE->getSubExpr(),
4794 SourceLocation());
4795 // Get the new text.
4796 std::string SStr;
4797 llvm::raw_string_ostream Buf(SStr);
4798 Replacement->printPretty(Buf, *Context);
4799 const std::string &Str = Buf.str();
4800
4801 printf("CAST = %s\n", &Str[0]);
4802 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4803 delete S;
4804 return Replacement;
4805 }
4806#endif
4807 // Return this stmt unmodified.
4808 return S;
4809}
4810
4811void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
4812 for (RecordDecl::field_iterator i = RD->field_begin(),
4813 e = RD->field_end(); i != e; ++i) {
4814 FieldDecl *FD = *i;
4815 if (isTopLevelBlockPointerType(FD->getType()))
4816 RewriteBlockPointerDecl(FD);
4817 if (FD->getType()->isObjCQualifiedIdType() ||
4818 FD->getType()->isObjCQualifiedInterfaceType())
4819 RewriteObjCQualifiedInterfaceTypes(FD);
4820 }
4821}
4822
4823/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4824/// main file of the input.
4825void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
4826 switch (D->getKind()) {
4827 case Decl::Function: {
4828 FunctionDecl *FD = cast<FunctionDecl>(D);
4829 if (FD->isOverloadedOperator())
4830 return;
4831
4832 // Since function prototypes don't have ParmDecl's, we check the function
4833 // prototype. This enables us to rewrite function declarations and
4834 // definitions using the same code.
4835 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
4836
4837 // FIXME: If this should support Obj-C++, support CXXTryStmt
4838 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
4839 CurFunctionDef = FD;
4840 CurFunctionDeclToDeclareForBlock = FD;
4841 CurrentBody = Body;
4842 Body =
4843 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4844 FD->setBody(Body);
4845 CurrentBody = 0;
4846 if (PropParentMap) {
4847 delete PropParentMap;
4848 PropParentMap = 0;
4849 }
4850 // This synthesizes and inserts the block "impl" struct, invoke function,
4851 // and any copy/dispose helper functions.
4852 InsertBlockLiteralsWithinFunction(FD);
4853 CurFunctionDef = 0;
4854 CurFunctionDeclToDeclareForBlock = 0;
4855 }
4856 break;
4857 }
4858 case Decl::ObjCMethod: {
4859 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
4860 if (CompoundStmt *Body = MD->getCompoundBody()) {
4861 CurMethodDef = MD;
4862 CurrentBody = Body;
4863 Body =
4864 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4865 MD->setBody(Body);
4866 CurrentBody = 0;
4867 if (PropParentMap) {
4868 delete PropParentMap;
4869 PropParentMap = 0;
4870 }
4871 InsertBlockLiteralsWithinMethod(MD);
4872 CurMethodDef = 0;
4873 }
4874 break;
4875 }
4876 case Decl::ObjCImplementation: {
4877 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
4878 ClassImplementation.push_back(CI);
4879 break;
4880 }
4881 case Decl::ObjCCategoryImpl: {
4882 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
4883 CategoryImplementation.push_back(CI);
4884 break;
4885 }
4886 case Decl::Var: {
4887 VarDecl *VD = cast<VarDecl>(D);
4888 RewriteObjCQualifiedInterfaceTypes(VD);
4889 if (isTopLevelBlockPointerType(VD->getType()))
4890 RewriteBlockPointerDecl(VD);
4891 else if (VD->getType()->isFunctionPointerType()) {
4892 CheckFunctionPointerDecl(VD->getType(), VD);
4893 if (VD->getInit()) {
4894 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
4895 RewriteCastExpr(CE);
4896 }
4897 }
4898 } else if (VD->getType()->isRecordType()) {
4899 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
4900 if (RD->isCompleteDefinition())
4901 RewriteRecordBody(RD);
4902 }
4903 if (VD->getInit()) {
4904 GlobalVarDecl = VD;
4905 CurrentBody = VD->getInit();
4906 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
4907 CurrentBody = 0;
4908 if (PropParentMap) {
4909 delete PropParentMap;
4910 PropParentMap = 0;
4911 }
4912 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
4913 GlobalVarDecl = 0;
4914
4915 // This is needed for blocks.
4916 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
4917 RewriteCastExpr(CE);
4918 }
4919 }
4920 break;
4921 }
4922 case Decl::TypeAlias:
4923 case Decl::Typedef: {
4924 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
4925 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
4926 RewriteBlockPointerDecl(TD);
4927 else if (TD->getUnderlyingType()->isFunctionPointerType())
4928 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4929 }
4930 break;
4931 }
4932 case Decl::CXXRecord:
4933 case Decl::Record: {
4934 RecordDecl *RD = cast<RecordDecl>(D);
4935 if (RD->isCompleteDefinition())
4936 RewriteRecordBody(RD);
4937 break;
4938 }
4939 default:
4940 break;
4941 }
4942 // Nothing yet.
4943}
4944
4945void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
4946 if (Diags.hasErrorOccurred())
4947 return;
4948
4949 RewriteInclude();
4950
4951 // Here's a great place to add any extra declarations that may be needed.
4952 // Write out meta data for each @protocol(<expr>).
4953 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
4954 E = ProtocolExprDecls.end(); I != E; ++I)
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00004955 RewriteObjCProtocolMetaData(*I, Preamble);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004956
4957 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
4958 if (ClassImplementation.size() || CategoryImplementation.size())
4959 RewriteImplementations();
4960
4961 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
4962 // we are done.
4963 if (const RewriteBuffer *RewriteBuf =
4964 Rewrite.getRewriteBufferFor(MainFileID)) {
4965 //printf("Changed:\n");
4966 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
4967 } else {
4968 llvm::errs() << "No changes\n";
4969 }
4970
4971 if (ClassImplementation.size() || CategoryImplementation.size() ||
4972 ProtocolExprDecls.size()) {
4973 // Rewrite Objective-c meta data*
4974 std::string ResultStr;
4975 RewriteMetaDataIntoBuffer(ResultStr);
4976 // Emit metadata.
4977 *OutFile << ResultStr;
4978 }
4979 OutFile->flush();
4980}
4981
4982void RewriteModernObjC::Initialize(ASTContext &context) {
4983 InitializeCommon(context);
4984
4985 // declaring objc_selector outside the parameter list removes a silly
4986 // scope related warning...
4987 if (IsHeader)
4988 Preamble = "#pragma once\n";
4989 Preamble += "struct objc_selector; struct objc_class;\n";
4990 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
4991 Preamble += "struct objc_object *superClass; ";
4992 if (LangOpts.MicrosoftExt) {
4993 // Add a constructor for creating temporary objects.
4994 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
4995 ": ";
4996 Preamble += "object(o), superClass(s) {} ";
4997 }
4998 Preamble += "};\n";
4999 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
5000 Preamble += "typedef struct objc_object Protocol;\n";
5001 Preamble += "#define _REWRITER_typedef_Protocol\n";
5002 Preamble += "#endif\n";
5003 if (LangOpts.MicrosoftExt) {
5004 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
5005 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
5006 } else
5007 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
5008 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
5009 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5010 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
5011 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
5012 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSend_stret";
5013 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5014 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSendSuper_stret";
5015 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
5016 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
5017 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5018 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
5019 Preamble += "(const char *);\n";
5020 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
5021 Preamble += "(struct objc_class *);\n";
5022 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
5023 Preamble += "(const char *);\n";
5024 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
5025 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
5026 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
5027 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
5028 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
5029 Preamble += "(struct objc_class *, struct objc_object *);\n";
5030 // @synchronized hooks.
5031 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
5032 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
5033 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
5034 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
5035 Preamble += "struct __objcFastEnumerationState {\n\t";
5036 Preamble += "unsigned long state;\n\t";
5037 Preamble += "void **itemsPtr;\n\t";
5038 Preamble += "unsigned long *mutationsPtr;\n\t";
5039 Preamble += "unsigned long extra[5];\n};\n";
5040 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
5041 Preamble += "#define __FASTENUMERATIONSTATE\n";
5042 Preamble += "#endif\n";
5043 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5044 Preamble += "struct __NSConstantStringImpl {\n";
5045 Preamble += " int *isa;\n";
5046 Preamble += " int flags;\n";
5047 Preamble += " char *str;\n";
5048 Preamble += " long length;\n";
5049 Preamble += "};\n";
5050 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5051 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5052 Preamble += "#else\n";
5053 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5054 Preamble += "#endif\n";
5055 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
5056 Preamble += "#endif\n";
5057 // Blocks preamble.
5058 Preamble += "#ifndef BLOCK_IMPL\n";
5059 Preamble += "#define BLOCK_IMPL\n";
5060 Preamble += "struct __block_impl {\n";
5061 Preamble += " void *isa;\n";
5062 Preamble += " int Flags;\n";
5063 Preamble += " int Reserved;\n";
5064 Preamble += " void *FuncPtr;\n";
5065 Preamble += "};\n";
5066 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
5067 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
5068 Preamble += "extern \"C\" __declspec(dllexport) "
5069 "void _Block_object_assign(void *, const void *, const int);\n";
5070 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
5071 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
5072 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
5073 Preamble += "#else\n";
5074 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
5075 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
5076 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
5077 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
5078 Preamble += "#endif\n";
5079 Preamble += "#endif\n";
5080 if (LangOpts.MicrosoftExt) {
5081 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
5082 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
5083 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
5084 Preamble += "#define __attribute__(X)\n";
5085 Preamble += "#endif\n";
5086 Preamble += "#define __weak\n";
5087 }
5088 else {
5089 Preamble += "#define __block\n";
5090 Preamble += "#define __weak\n";
5091 }
5092 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
5093 // as this avoids warning in any 64bit/32bit compilation model.
5094 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
5095}
5096
5097/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
5098/// ivar offset.
5099void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
5100 std::string &Result) {
5101 if (ivar->isBitField()) {
5102 // FIXME: The hack below doesn't work for bitfields. For now, we simply
5103 // place all bitfields at offset 0.
5104 Result += "0";
5105 } else {
5106 Result += "__OFFSETOFIVAR__(struct ";
5107 Result += ivar->getContainingInterface()->getNameAsString();
5108 if (LangOpts.MicrosoftExt)
5109 Result += "_IMPL";
5110 Result += ", ";
5111 Result += ivar->getNameAsString();
5112 Result += ")";
5113 }
5114}
5115
5116/// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
5117/// struct _prop_t {
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005118/// const char *name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005119/// char *attributes;
5120/// }
5121
5122/// struct _prop_list_t {
5123/// uint32_t entsize; // sizeof(struct _prop_t)
5124/// uint32_t count_of_properties;
5125/// struct _prop_t prop_list[count_of_properties];
5126/// }
5127
5128/// struct _protocol_t;
5129
5130/// struct _protocol_list_t {
5131/// long protocol_count; // Note, this is 32/64 bit
5132/// struct _protocol_t * protocol_list[protocol_count];
5133/// }
5134
5135/// struct _objc_method {
5136/// SEL _cmd;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005137/// const char *method_type;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005138/// char *_imp;
5139/// }
5140
5141/// struct _method_list_t {
5142/// uint32_t entsize; // sizeof(struct _objc_method)
5143/// uint32_t method_count;
5144/// struct _objc_method method_list[method_count];
5145/// }
5146
5147/// struct _protocol_t {
5148/// id isa; // NULL
5149/// const char * const protocol_name;
5150/// const struct _protocol_list_t * protocol_list; // super protocols
5151/// const struct method_list_t * const instance_methods;
5152/// const struct method_list_t * const class_methods;
5153/// const struct method_list_t *optionalInstanceMethods;
5154/// const struct method_list_t *optionalClassMethods;
5155/// const struct _prop_list_t * properties;
5156/// const uint32_t size; // sizeof(struct _protocol_t)
5157/// const uint32_t flags; // = 0
5158/// const char ** extendedMethodTypes;
5159/// }
5160
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005161/// struct _ivar_t {
5162/// unsigned long int *offset; // pointer to ivar offset location
Fariborz Jahanianae932952012-02-10 20:47:10 +00005163/// const char *name;
5164/// const char *type;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005165/// uint32_t alignment;
5166/// uint32_t size;
5167/// }
5168
5169/// struct _ivar_list_t {
5170/// uint32 entsize; // sizeof(struct _ivar_t)
5171/// uint32 count;
Fariborz Jahanianae932952012-02-10 20:47:10 +00005172/// struct _ivar_t list[count];
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005173/// }
5174
5175/// struct _class_ro_t {
5176/// uint32_t const flags;
5177/// uint32_t const instanceStart;
5178/// uint32_t const instanceSize;
5179/// uint32_t const reserved; // only when building for 64bit targets
5180/// const uint8_t * const ivarLayout;
5181/// const char *const name;
5182/// const struct _method_list_t * const baseMethods;
5183/// const struct _objc_protocol_list *const baseProtocols;
5184/// const struct _ivar_list_t *const ivars;
5185/// const uint8_t * const weakIvarLayout;
5186/// const struct _prop_list_t * const properties;
5187/// }
5188
5189/// struct _class_t {
5190/// struct _class_t *isa;
5191/// struct _class_t * const superclass;
5192/// void *cache;
5193/// IMP *vtable;
5194/// struct class_ro_t *ro;
5195/// }
5196
5197/// struct _category_t {
5198/// const char * const name;
5199/// struct _class_t *const cls;
5200/// const struct _method_list_t * const instance_methods;
5201/// const struct _method_list_t * const class_methods;
5202/// const struct _protocol_list_t * const protocols;
5203/// const struct _prop_list_t * const properties;
5204/// }
5205
5206/// MessageRefTy - LLVM for:
5207/// struct _message_ref_t {
5208/// IMP messenger;
5209/// SEL name;
5210/// };
5211
5212/// SuperMessageRefTy - LLVM for:
5213/// struct _super_message_ref_t {
5214/// SUPER_IMP messenger;
5215/// SEL name;
5216/// };
5217
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005218static void WriteModernMetadataDeclarations(std::string &Result) {
5219 static bool meta_data_declared = false;
5220 if (meta_data_declared)
5221 return;
5222
5223 Result += "\nstruct _prop_t {\n";
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005224 Result += "\tconst char *name;\n";
5225 Result += "\tconst char *attributes;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005226 Result += "};\n";
5227
5228 Result += "\nstruct _protocol_t;\n";
5229
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005230 Result += "\nstruct _objc_method {\n";
5231 Result += "\tstruct objc_selector * _cmd;\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005232 Result += "\tconst char *method_type;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005233 Result += "\tchar *_imp;\n";
5234 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005235
5236 Result += "\nstruct _protocol_t {\n";
5237 Result += "\tvoid * isa; // NULL\n";
5238 Result += "\tconst char * const protocol_name;\n";
5239 Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
5240 Result += "\tconst struct method_list_t * const instance_methods;\n";
5241 Result += "\tconst struct method_list_t * const class_methods;\n";
5242 Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
5243 Result += "\tconst struct method_list_t *optionalClassMethods;\n";
5244 Result += "\tconst struct _prop_list_t * properties;\n";
5245 Result += "\tconst unsigned int size; // sizeof(struct _protocol_t)\n";
5246 Result += "\tconst unsigned int flags; // = 0\n";
5247 Result += "\tconst char ** extendedMethodTypes;\n";
5248 Result += "};\n";
5249
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005250 Result += "\nstruct _ivar_t {\n";
5251 Result += "\tunsigned long int *offset; // pointer to ivar offset location\n";
Fariborz Jahanianae932952012-02-10 20:47:10 +00005252 Result += "\tconst char *name;\n";
5253 Result += "\tconst char *type;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005254 Result += "\tunsigned int alignment;\n";
5255 Result += "\tunsigned int size;\n";
5256 Result += "};\n";
5257
5258 Result += "\nstruct _class_ro_t {\n";
5259 Result += "\tunsigned int const flags;\n";
5260 Result += "\tunsigned int instanceStart;\n";
5261 Result += "\tunsigned int const instanceSize;\n";
5262 Result += "\tunsigned int const reserved; // only when building for 64bit targets\n";
5263 Result += "\tconst unsigned char * const ivarLayout;\n";
5264 Result += "\tconst char *const name;\n";
5265 Result += "\tconst struct _method_list_t * const baseMethods;\n";
5266 Result += "\tconst struct _objc_protocol_list *const baseProtocols;\n";
5267 Result += "\tconst struct _ivar_list_t *const ivars;\n";
5268 Result += "\tconst unsigned char *const weakIvarLayout;\n";
5269 Result += "\tconst struct _prop_list_t *const properties;\n";
5270 Result += "};\n";
5271
5272 Result += "\nstruct _class_t {\n";
5273 Result += "\tstruct _class_t *isa;\n";
5274 Result += "\tstruct _class_t *const superclass;\n";
5275 Result += "\tvoid *cache;\n";
5276 Result += "\tvoid *vtable;\n";
5277 Result += "\tstruct class_ro_t *ro;\n";
5278 Result += "};\n";
5279
5280 Result += "\nstruct _category_t {\n";
5281 Result += "\tconst char * const name;\n";
5282 Result += "\tstruct _class_t *const cls;\n";
5283 Result += "\tconst struct _method_list_t *const instance_methods;\n";
5284 Result += "\tconst struct _method_list_t *const class_methods;\n";
5285 Result += "\tconst struct _protocol_list_t *const protocols;\n";
5286 Result += "\tconst struct _prop_list_t *const properties;\n";
5287 Result += "};\n";
5288
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005289 meta_data_declared = true;
5290}
5291
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005292static void Write_protocol_list_t_TypeDecl(std::string &Result,
5293 long super_protocol_count) {
5294 Result += "struct /*_protocol_list_t*/"; Result += " {\n";
5295 Result += "\tlong protocol_count; // Note, this is 32/64 bit\n";
5296 Result += "\tstruct _protocol_t *super_protocols[";
5297 Result += utostr(super_protocol_count); Result += "];\n";
5298 Result += "}";
5299}
5300
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005301static void Write_method_list_t_TypeDecl(std::string &Result,
5302 unsigned int method_count) {
5303 Result += "struct /*_method_list_t*/"; Result += " {\n";
5304 Result += "\tunsigned int entsize; // sizeof(struct _objc_method)\n";
5305 Result += "\tunsigned int method_count;\n";
5306 Result += "\tstruct _objc_method method_list[";
5307 Result += utostr(method_count); Result += "];\n";
5308 Result += "}";
5309}
5310
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005311static void Write__prop_list_t_TypeDecl(std::string &Result,
5312 unsigned int property_count) {
5313 Result += "struct /*_prop_list_t*/"; Result += " {\n";
5314 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
5315 Result += "\tunsigned int count_of_properties;\n";
5316 Result += "\tstruct _prop_t prop_list[";
5317 Result += utostr(property_count); Result += "];\n";
5318 Result += "}";
5319}
5320
Fariborz Jahanianae932952012-02-10 20:47:10 +00005321static void Write__ivar_list_t_TypeDecl(std::string &Result,
5322 unsigned int ivar_count) {
5323 Result += "struct /*_ivar_list_t*/"; Result += " {\n";
5324 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
5325 Result += "\tunsigned int count;\n";
5326 Result += "\tstruct _ivar_t ivar_list[";
5327 Result += utostr(ivar_count); Result += "];\n";
5328 Result += "}";
5329}
5330
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005331static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result,
5332 ArrayRef<ObjCProtocolDecl *> SuperProtocols,
5333 StringRef VarName,
5334 StringRef ProtocolName) {
5335 if (SuperProtocols.size() > 0) {
5336 Result += "\nstatic ";
5337 Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size());
5338 Result += " "; Result += VarName;
5339 Result += ProtocolName;
5340 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5341 Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n";
5342 for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) {
5343 ObjCProtocolDecl *SuperPD = SuperProtocols[i];
5344 Result += "\t&"; Result += "_OBJC_PROTOCOL_";
5345 Result += SuperPD->getNameAsString();
5346 if (i == e-1)
5347 Result += "\n};\n";
5348 else
5349 Result += ",\n";
5350 }
5351 }
5352}
5353
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005354static void Write_method_list_t_initializer(ASTContext *Context, std::string &Result,
5355 ArrayRef<ObjCMethodDecl *> Methods,
5356 StringRef VarName,
5357 StringRef ProtocolName) {
5358 if (Methods.size() > 0) {
5359 Result += "\nstatic ";
5360 Write_method_list_t_TypeDecl(Result, Methods.size());
5361 Result += " "; Result += VarName;
5362 Result += ProtocolName;
5363 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5364 Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
5365 Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
5366 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
5367 ObjCMethodDecl *MD = Methods[i];
5368 if (i == 0)
5369 Result += "\t{{(struct objc_selector *)\"";
5370 else
5371 Result += "\t{(struct objc_selector *)\"";
5372 Result += (MD)->getSelector().getAsString(); Result += "\"";
5373 Result += ", ";
5374 std::string MethodTypeString;
5375 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString);
5376 Result += "\""; Result += MethodTypeString; Result += "\"";
5377 Result += ", ";
5378 // FIXME is _imp always null here?
5379 if (i == e-1)
5380 Result += "0}}\n";
5381 else
5382 Result += "0},\n";
5383 }
5384 Result += "};\n";
5385 }
5386}
5387
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005388static void Write__prop_list_t_initializer(RewriteModernObjC &RewriteObj,
5389 ASTContext *Context, std::string &Result,
5390 ArrayRef<ObjCPropertyDecl *> Properties,
5391 const Decl *Container,
5392 StringRef VarName,
5393 StringRef ProtocolName) {
5394 if (Properties.size() > 0) {
5395 Result += "\nstatic ";
5396 Write__prop_list_t_TypeDecl(Result, Properties.size());
5397 Result += " "; Result += VarName;
5398 Result += ProtocolName;
5399 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5400 Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
5401 Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
5402 for (unsigned i = 0, e = Properties.size(); i < e; i++) {
5403 ObjCPropertyDecl *PropDecl = Properties[i];
5404 if (i == 0)
5405 Result += "\t{{\"";
5406 else
5407 Result += "\t{\"";
5408 Result += PropDecl->getName(); Result += "\",";
5409 std::string PropertyTypeString, QuotePropertyTypeString;
5410 Context->getObjCEncodingForPropertyDecl(PropDecl, Container, PropertyTypeString);
5411 RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
5412 Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
5413 if (i == e-1)
5414 Result += "}}\n";
5415 else
5416 Result += "},\n";
5417 }
5418 Result += "};\n";
5419 }
5420}
5421
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00005422static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj,
5423 ASTContext *Context, std::string &Result,
5424 ArrayRef<ObjCMethodDecl *> Methods,
5425 StringRef VarName,
5426 StringRef ProtocolName) {
5427 if (Methods.size() == 0)
5428 return;
5429
5430 Result += "\nstatic const char *";
5431 Result += VarName; Result += ProtocolName;
5432 Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
5433 Result += "{\n";
5434 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
5435 ObjCMethodDecl *MD = Methods[i];
5436 std::string MethodTypeString, QuoteMethodTypeString;
5437 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString, true);
5438 RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString);
5439 Result += "\t\""; Result += QuoteMethodTypeString; Result += "\"";
5440 if (i == e-1)
5441 Result += "\n};\n";
5442 else {
5443 Result += ",\n";
5444 }
5445 }
5446}
5447
Fariborz Jahanianae932952012-02-10 20:47:10 +00005448static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj,
5449 ASTContext *Context, std::string &Result,
5450 ArrayRef<ObjCIvarDecl *> Ivars,
5451 StringRef VarName,
5452 StringRef ClassName) {
5453 if (Ivars.size() > 0) {
5454 Result += "\nstatic ";
5455 Write__ivar_list_t_TypeDecl(Result, Ivars.size());
5456 Result += " "; Result += VarName;
5457 Result += ClassName;
5458 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5459 Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n";
5460 Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n";
5461 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
5462 ObjCIvarDecl *IvarDecl = Ivars[i];
5463 if (i == 0)
5464 Result += "\t{{";
5465 else
5466 Result += "\t {";
5467 // FIXME: // pointer to ivar offset location
5468 Result += "(unsigned long int *)0, ";
5469
5470 Result += "\""; Result += IvarDecl->getName(); Result += "\", ";
5471 std::string IvarTypeString, QuoteIvarTypeString;
5472 Context->getObjCEncodingForType(IvarDecl->getType(), IvarTypeString,
5473 IvarDecl);
5474 RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString);
5475 Result += "\""; Result += QuoteIvarTypeString; Result += "\", ";
5476
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00005477 // FIXME. this alignment represents the host alignment and need be changed to
5478 // represent the target alignment.
5479 unsigned Align = Context->getTypeAlign(IvarDecl->getType())/8;
5480 Align = llvm::Log2_32(Align);
Fariborz Jahanianae932952012-02-10 20:47:10 +00005481 Result += llvm::utostr(Align); Result += ", ";
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00005482 CharUnits Size = Context->getTypeSizeInChars(IvarDecl->getType());
5483 Result += llvm::utostr(Size.getQuantity());
Fariborz Jahanianae932952012-02-10 20:47:10 +00005484 if (i == e-1)
5485 Result += "}}\n";
5486 else
5487 Result += "},\n";
5488 }
5489 Result += "};\n";
5490 }
5491}
5492
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005493/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005494void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl,
5495 std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005496
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005497 // Do not synthesize the protocol more than once.
5498 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
5499 return;
Fariborz Jahanian82848c22012-02-08 00:50:52 +00005500 WriteModernMetadataDeclarations(Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005501
5502 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
5503 PDecl = Def;
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005504 // Must write out all protocol definitions in current qualifier list,
5505 // and in their nested qualifiers before writing out current definition.
5506 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
5507 E = PDecl->protocol_end(); I != E; ++I)
5508 RewriteObjCProtocolMetaData(*I, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005509
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005510 // Construct method lists.
5511 std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
5512 std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
5513 for (ObjCProtocolDecl::instmeth_iterator
5514 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
5515 I != E; ++I) {
5516 ObjCMethodDecl *MD = *I;
5517 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
5518 OptInstanceMethods.push_back(MD);
5519 } else {
5520 InstanceMethods.push_back(MD);
5521 }
5522 }
5523
5524 for (ObjCProtocolDecl::classmeth_iterator
5525 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
5526 I != E; ++I) {
5527 ObjCMethodDecl *MD = *I;
5528 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
5529 OptClassMethods.push_back(MD);
5530 } else {
5531 ClassMethods.push_back(MD);
5532 }
5533 }
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00005534 std::vector<ObjCMethodDecl *> AllMethods;
5535 for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++)
5536 AllMethods.push_back(InstanceMethods[i]);
5537 for (unsigned i = 0, e = ClassMethods.size(); i < e; i++)
5538 AllMethods.push_back(ClassMethods[i]);
5539 for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++)
5540 AllMethods.push_back(OptInstanceMethods[i]);
5541 for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++)
5542 AllMethods.push_back(OptClassMethods[i]);
5543
5544 Write__extendedMethodTypes_initializer(*this, Context, Result,
5545 AllMethods,
5546 "_OBJC_PROTOCOL_METHOD_TYPES_",
5547 PDecl->getNameAsString());
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005548 // Protocol's super protocol list
5549 std::vector<ObjCProtocolDecl *> SuperProtocols;
5550 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
5551 E = PDecl->protocol_end(); I != E; ++I)
5552 SuperProtocols.push_back(*I);
5553
5554 Write_protocol_list_initializer(Context, Result, SuperProtocols,
5555 "_OBJC_PROTOCOL_REFS_",
5556 PDecl->getNameAsString());
5557
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005558 Write_method_list_t_initializer(Context, Result, InstanceMethods,
5559 "_OBJC_PROTOCOL_INSTANCE_METHODS_",
5560 PDecl->getNameAsString());
5561
5562 Write_method_list_t_initializer(Context, Result, ClassMethods,
5563 "_OBJC_PROTOCOL_CLASS_METHODS_",
5564 PDecl->getNameAsString());
5565
5566 Write_method_list_t_initializer(Context, Result, OptInstanceMethods,
5567 "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_",
5568 PDecl->getNameAsString());
5569
5570 Write_method_list_t_initializer(Context, Result, OptClassMethods,
5571 "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
5572 PDecl->getNameAsString());
5573
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005574 // Protocol's property metadata.
5575 std::vector<ObjCPropertyDecl *> ProtocolProperties;
5576 for (ObjCContainerDecl::prop_iterator I = PDecl->prop_begin(),
5577 E = PDecl->prop_end(); I != E; ++I)
5578 ProtocolProperties.push_back(*I);
5579
5580 Write__prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
5581 /* Container */0,
5582 "_OBJC_PROTOCOL_PROPERTIES_",
5583 PDecl->getNameAsString());
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005584
Fariborz Jahanian82848c22012-02-08 00:50:52 +00005585 // Writer out root metadata for current protocol: struct _protocol_t
5586 Result += "\nstatic struct _protocol_t _OBJC_PROTOCOL_";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005587 Result += PDecl->getNameAsString();
Fariborz Jahanian82848c22012-02-08 00:50:52 +00005588 Result += " __attribute__ ((used, section (\"__DATA,__datacoal_nt,coalesced\"))) = {\n";
5589 Result += "\t0,\n"; // id is; is null
5590 Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n";
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005591 if (SuperProtocols.size() > 0) {
5592 Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_";
5593 Result += PDecl->getNameAsString(); Result += ",\n";
5594 }
5595 else
5596 Result += "\t0,\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00005597 if (InstanceMethods.size() > 0) {
5598 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
5599 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005600 }
5601 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00005602 Result += "\t0,\n";
5603
5604 if (ClassMethods.size() > 0) {
5605 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_";
5606 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005607 }
5608 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00005609 Result += "\t0,\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005610
Fariborz Jahanian82848c22012-02-08 00:50:52 +00005611 if (OptInstanceMethods.size() > 0) {
5612 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_";
5613 Result += PDecl->getNameAsString(); Result += ",\n";
5614 }
5615 else
5616 Result += "\t0,\n";
5617
5618 if (OptClassMethods.size() > 0) {
5619 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_";
5620 Result += PDecl->getNameAsString(); Result += ",\n";
5621 }
5622 else
5623 Result += "\t0,\n";
5624
5625 if (ProtocolProperties.size() > 0) {
5626 Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_";
5627 Result += PDecl->getNameAsString(); Result += ",\n";
5628 }
5629 else
5630 Result += "\t0,\n";
5631
5632 Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n";
5633 Result += "\t0,\n";
5634
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00005635 if (AllMethods.size() > 0) {
5636 Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_";
5637 Result += PDecl->getNameAsString();
5638 Result += "\n};\n";
5639 }
5640 else
5641 Result += "\t0\n};\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00005642
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005643 // Mark this protocol as having been generated.
5644 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()))
5645 llvm_unreachable("protocol already synthesized");
5646
5647}
5648
5649void RewriteModernObjC::RewriteObjCProtocolListMetaData(
5650 const ObjCList<ObjCProtocolDecl> &Protocols,
5651 StringRef prefix, StringRef ClassName,
5652 std::string &Result) {
5653 if (Protocols.empty()) return;
5654
5655 for (unsigned i = 0; i != Protocols.size(); i++)
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005656 RewriteObjCProtocolMetaData(Protocols[i], Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005657
5658 // Output the top lovel protocol meta-data for the class.
5659 /* struct _objc_protocol_list {
5660 struct _objc_protocol_list *next;
5661 int protocol_count;
5662 struct _objc_protocol *class_protocols[];
5663 }
5664 */
5665 Result += "\nstatic struct {\n";
5666 Result += "\tstruct _objc_protocol_list *next;\n";
5667 Result += "\tint protocol_count;\n";
5668 Result += "\tstruct _objc_protocol *class_protocols[";
5669 Result += utostr(Protocols.size());
5670 Result += "];\n} _OBJC_";
5671 Result += prefix;
5672 Result += "_PROTOCOLS_";
5673 Result += ClassName;
5674 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
5675 "{\n\t0, ";
5676 Result += utostr(Protocols.size());
5677 Result += "\n";
5678
5679 Result += "\t,{&_OBJC_PROTOCOL_";
5680 Result += Protocols[0]->getNameAsString();
5681 Result += " \n";
5682
5683 for (unsigned i = 1; i != Protocols.size(); i++) {
5684 Result += "\t ,&_OBJC_PROTOCOL_";
5685 Result += Protocols[i]->getNameAsString();
5686 Result += "\n";
5687 }
5688 Result += "\t }\n};\n";
5689}
5690
5691void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
5692 std::string &Result) {
5693 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
5694
5695 // Explicitly declared @interface's are already synthesized.
Fariborz Jahanianae932952012-02-10 20:47:10 +00005696 if (CDecl->isImplicitInterfaceDecl())
5697 assert(false &&
5698 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00005699
Fariborz Jahanianae932952012-02-10 20:47:10 +00005700 WriteModernMetadataDeclarations(Result);
5701 SmallVector<ObjCIvarDecl *, 8> IVars;
5702
5703 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
5704 IVD; IVD = IVD->getNextIvar()) {
5705 // Ignore unnamed bit-fields.
5706 if (!IVD->getDeclName())
5707 continue;
5708 IVars.push_back(IVD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005709 }
5710
Fariborz Jahanianae932952012-02-10 20:47:10 +00005711 Write__ivar_list_t_initializer(*this, Context, Result, IVars,
5712 "_OBJC_INSTANCE_VARIABLES_",
5713 CDecl->getNameAsString());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005714}
5715
5716void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
5717 int ClsDefCount = ClassImplementation.size();
5718 int CatDefCount = CategoryImplementation.size();
5719
5720 // For each implemented class, write out all its meta data.
5721 for (int i = 0; i < ClsDefCount; i++)
5722 RewriteObjCClassMetaData(ClassImplementation[i], Result);
5723
5724 // For each implemented category, write out all its meta data.
5725 for (int i = 0; i < CatDefCount; i++)
5726 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
5727
5728 // Write objc_symtab metadata
5729 /*
5730 struct _objc_symtab
5731 {
5732 long sel_ref_cnt;
5733 SEL *refs;
5734 short cls_def_cnt;
5735 short cat_def_cnt;
5736 void *defs[cls_def_cnt + cat_def_cnt];
5737 };
5738 */
5739
5740 Result += "\nstruct _objc_symtab {\n";
5741 Result += "\tlong sel_ref_cnt;\n";
5742 Result += "\tSEL *refs;\n";
5743 Result += "\tshort cls_def_cnt;\n";
5744 Result += "\tshort cat_def_cnt;\n";
5745 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
5746 Result += "};\n\n";
5747
5748 Result += "static struct _objc_symtab "
5749 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
5750 Result += "\t0, 0, " + utostr(ClsDefCount)
5751 + ", " + utostr(CatDefCount) + "\n";
5752 for (int i = 0; i < ClsDefCount; i++) {
5753 Result += "\t,&_OBJC_CLASS_";
5754 Result += ClassImplementation[i]->getNameAsString();
5755 Result += "\n";
5756 }
5757
5758 for (int i = 0; i < CatDefCount; i++) {
5759 Result += "\t,&_OBJC_CATEGORY_";
5760 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
5761 Result += "_";
5762 Result += CategoryImplementation[i]->getNameAsString();
5763 Result += "\n";
5764 }
5765
5766 Result += "};\n\n";
5767
5768 // Write objc_module metadata
5769
5770 /*
5771 struct _objc_module {
5772 long version;
5773 long size;
5774 const char *name;
5775 struct _objc_symtab *symtab;
5776 }
5777 */
5778
5779 Result += "\nstruct _objc_module {\n";
5780 Result += "\tlong version;\n";
5781 Result += "\tlong size;\n";
5782 Result += "\tconst char *name;\n";
5783 Result += "\tstruct _objc_symtab *symtab;\n";
5784 Result += "};\n\n";
5785 Result += "static struct _objc_module "
5786 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
5787 Result += "\t" + utostr(OBJC_ABI_VERSION) +
5788 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
5789 Result += "};\n\n";
5790
5791 if (LangOpts.MicrosoftExt) {
5792 if (ProtocolExprDecls.size()) {
5793 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
5794 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
5795 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
5796 E = ProtocolExprDecls.end(); I != E; ++I) {
5797 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
5798 Result += (*I)->getNameAsString();
5799 Result += " = &_OBJC_PROTOCOL_";
5800 Result += (*I)->getNameAsString();
5801 Result += ";\n";
5802 }
5803 Result += "#pragma data_seg(pop)\n\n";
5804 }
5805 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
5806 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
5807 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
5808 Result += "&_OBJC_MODULES;\n";
5809 Result += "#pragma data_seg(pop)\n\n";
5810 }
5811}
5812
5813/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
5814/// implementation.
5815void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
5816 std::string &Result) {
5817 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
5818 // Find category declaration for this implementation.
5819 ObjCCategoryDecl *CDecl;
5820 for (CDecl = ClassDecl->getCategoryList(); CDecl;
5821 CDecl = CDecl->getNextClassCategory())
5822 if (CDecl->getIdentifier() == IDecl->getIdentifier())
5823 break;
5824
5825 std::string FullCategoryName = ClassDecl->getNameAsString();
5826 FullCategoryName += '_';
5827 FullCategoryName += IDecl->getNameAsString();
5828
5829 // Build _objc_method_list for class's instance methods if needed
5830 SmallVector<ObjCMethodDecl *, 32>
5831 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
5832
5833 // If any of our property implementations have associated getters or
5834 // setters, produce metadata for them as well.
5835 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
5836 PropEnd = IDecl->propimpl_end();
5837 Prop != PropEnd; ++Prop) {
5838 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5839 continue;
5840 if (!(*Prop)->getPropertyIvarDecl())
5841 continue;
5842 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
5843 if (!PD)
5844 continue;
5845 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
5846 InstanceMethods.push_back(Getter);
5847 if (PD->isReadOnly())
5848 continue;
5849 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
5850 InstanceMethods.push_back(Setter);
5851 }
5852 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
5853 true, "CATEGORY_", FullCategoryName.c_str(),
5854 Result);
5855
5856 // Build _objc_method_list for class's class methods if needed
5857 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
5858 false, "CATEGORY_", FullCategoryName.c_str(),
5859 Result);
5860
5861 // Protocols referenced in class declaration?
5862 // Null CDecl is case of a category implementation with no category interface
5863 if (CDecl)
5864 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
5865 FullCategoryName, Result);
5866 /* struct _objc_category {
5867 char *category_name;
5868 char *class_name;
5869 struct _objc_method_list *instance_methods;
5870 struct _objc_method_list *class_methods;
5871 struct _objc_protocol_list *protocols;
5872 // Objective-C 1.0 extensions
5873 uint32_t size; // sizeof (struct _objc_category)
5874 struct _objc_property_list *instance_properties; // category's own
5875 // @property decl.
5876 };
5877 */
5878
5879 static bool objc_category = false;
5880 if (!objc_category) {
5881 Result += "\nstruct _objc_category {\n";
5882 Result += "\tchar *category_name;\n";
5883 Result += "\tchar *class_name;\n";
5884 Result += "\tstruct _objc_method_list *instance_methods;\n";
5885 Result += "\tstruct _objc_method_list *class_methods;\n";
5886 Result += "\tstruct _objc_protocol_list *protocols;\n";
5887 Result += "\tunsigned int size;\n";
5888 Result += "\tstruct _objc_property_list *instance_properties;\n";
5889 Result += "};\n";
5890 objc_category = true;
5891 }
5892 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
5893 Result += FullCategoryName;
5894 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
5895 Result += IDecl->getNameAsString();
5896 Result += "\"\n\t, \"";
5897 Result += ClassDecl->getNameAsString();
5898 Result += "\"\n";
5899
5900 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
5901 Result += "\t, (struct _objc_method_list *)"
5902 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
5903 Result += FullCategoryName;
5904 Result += "\n";
5905 }
5906 else
5907 Result += "\t, 0\n";
5908 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
5909 Result += "\t, (struct _objc_method_list *)"
5910 "&_OBJC_CATEGORY_CLASS_METHODS_";
5911 Result += FullCategoryName;
5912 Result += "\n";
5913 }
5914 else
5915 Result += "\t, 0\n";
5916
5917 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
5918 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
5919 Result += FullCategoryName;
5920 Result += "\n";
5921 }
5922 else
5923 Result += "\t, 0\n";
5924 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
5925}
5926
5927// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
5928/// class methods.
5929template<typename MethodIterator>
5930void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
5931 MethodIterator MethodEnd,
5932 bool IsInstanceMethod,
5933 StringRef prefix,
5934 StringRef ClassName,
5935 std::string &Result) {
5936 if (MethodBegin == MethodEnd) return;
5937
5938 if (!objc_impl_method) {
5939 /* struct _objc_method {
5940 SEL _cmd;
5941 char *method_types;
5942 void *_imp;
5943 }
5944 */
5945 Result += "\nstruct _objc_method {\n";
5946 Result += "\tSEL _cmd;\n";
5947 Result += "\tchar *method_types;\n";
5948 Result += "\tvoid *_imp;\n";
5949 Result += "};\n";
5950
5951 objc_impl_method = true;
5952 }
5953
5954 // Build _objc_method_list for class's methods if needed
5955
5956 /* struct {
5957 struct _objc_method_list *next_method;
5958 int method_count;
5959 struct _objc_method method_list[];
5960 }
5961 */
5962 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
5963 Result += "\nstatic struct {\n";
5964 Result += "\tstruct _objc_method_list *next_method;\n";
5965 Result += "\tint method_count;\n";
5966 Result += "\tstruct _objc_method method_list[";
5967 Result += utostr(NumMethods);
5968 Result += "];\n} _OBJC_";
5969 Result += prefix;
5970 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
5971 Result += "_METHODS_";
5972 Result += ClassName;
5973 Result += " __attribute__ ((used, section (\"__OBJC, __";
5974 Result += IsInstanceMethod ? "inst" : "cls";
5975 Result += "_meth\")))= ";
5976 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
5977
5978 Result += "\t,{{(SEL)\"";
5979 Result += (*MethodBegin)->getSelector().getAsString().c_str();
5980 std::string MethodTypeString;
5981 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
5982 Result += "\", \"";
5983 Result += MethodTypeString;
5984 Result += "\", (void *)";
5985 Result += MethodInternalNames[*MethodBegin];
5986 Result += "}\n";
5987 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
5988 Result += "\t ,{(SEL)\"";
5989 Result += (*MethodBegin)->getSelector().getAsString().c_str();
5990 std::string MethodTypeString;
5991 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
5992 Result += "\", \"";
5993 Result += MethodTypeString;
5994 Result += "\", (void *)";
5995 Result += MethodInternalNames[*MethodBegin];
5996 Result += "}\n";
5997 }
5998 Result += "\t }\n};\n";
5999}
6000
6001Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
6002 SourceRange OldRange = IV->getSourceRange();
6003 Expr *BaseExpr = IV->getBase();
6004
6005 // Rewrite the base, but without actually doing replaces.
6006 {
6007 DisableReplaceStmtScope S(*this);
6008 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
6009 IV->setBase(BaseExpr);
6010 }
6011
6012 ObjCIvarDecl *D = IV->getDecl();
6013
6014 Expr *Replacement = IV;
6015 if (CurMethodDef) {
6016 if (BaseExpr->getType()->isObjCObjectPointerType()) {
6017 const ObjCInterfaceType *iFaceDecl =
6018 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
6019 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
6020 // lookup which class implements the instance variable.
6021 ObjCInterfaceDecl *clsDeclared = 0;
6022 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
6023 clsDeclared);
6024 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
6025
6026 // Synthesize an explicit cast to gain access to the ivar.
6027 std::string RecName = clsDeclared->getIdentifier()->getName();
6028 RecName += "_IMPL";
6029 IdentifierInfo *II = &Context->Idents.get(RecName);
6030 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
6031 SourceLocation(), SourceLocation(),
6032 II);
6033 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
6034 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
6035 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
6036 CK_BitCast,
6037 IV->getBase());
6038 // Don't forget the parens to enforce the proper binding.
6039 ParenExpr *PE = new (Context) ParenExpr(OldRange.getBegin(),
6040 OldRange.getEnd(),
6041 castExpr);
6042 if (IV->isFreeIvar() &&
6043 declaresSameEntity(CurMethodDef->getClassInterface(), iFaceDecl->getDecl())) {
6044 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
6045 IV->getLocation(),
6046 D->getType(),
6047 VK_LValue, OK_Ordinary);
6048 Replacement = ME;
6049 } else {
6050 IV->setBase(PE);
6051 }
6052 }
6053 } else { // we are outside a method.
6054 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
6055
6056 // Explicit ivar refs need to have a cast inserted.
6057 // FIXME: consider sharing some of this code with the code above.
6058 if (BaseExpr->getType()->isObjCObjectPointerType()) {
6059 const ObjCInterfaceType *iFaceDecl =
6060 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
6061 // lookup which class implements the instance variable.
6062 ObjCInterfaceDecl *clsDeclared = 0;
6063 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
6064 clsDeclared);
6065 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
6066
6067 // Synthesize an explicit cast to gain access to the ivar.
6068 std::string RecName = clsDeclared->getIdentifier()->getName();
6069 RecName += "_IMPL";
6070 IdentifierInfo *II = &Context->Idents.get(RecName);
6071 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
6072 SourceLocation(), SourceLocation(),
6073 II);
6074 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
6075 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
6076 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
6077 CK_BitCast,
6078 IV->getBase());
6079 // Don't forget the parens to enforce the proper binding.
6080 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
6081 IV->getBase()->getLocEnd(), castExpr);
6082 // Cannot delete IV->getBase(), since PE points to it.
6083 // Replace the old base with the cast. This is important when doing
6084 // embedded rewrites. For example, [newInv->_container addObject:0].
6085 IV->setBase(PE);
6086 }
6087 }
6088
6089 ReplaceStmtWithRange(IV, Replacement, OldRange);
6090 return Replacement;
6091}
6092