blob: ffadfd3c1a006b1e2adb805c1db553d241f743c4 [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
Ted Kremenek305c6132012-09-01 05:09:24 +000014#include "clang/Rewrite/Frontend/ASTConsumers.h"
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000015#include "clang/AST/AST.h"
16#include "clang/AST/ASTConsumer.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000017#include "clang/AST/Attr.h"
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000018#include "clang/AST/ParentMap.h"
Jordan Rose3f6f51e2013-02-08 22:30:41 +000019#include "clang/Basic/CharInfo.h"
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000020#include "clang/Basic/Diagnostic.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000021#include "clang/Basic/IdentifierTable.h"
22#include "clang/Basic/SourceManager.h"
Benjamin Kramer9852f582012-12-01 16:35:25 +000023#include "clang/Basic/TargetInfo.h"
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000024#include "clang/Lex/Lexer.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000025#include "clang/Rewrite/Core/Rewriter.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000026#include "llvm/ADT/DenseSet.h"
27#include "llvm/ADT/OwningPtr.h"
28#include "llvm/ADT/SmallPtrSet.h"
29#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000030#include "llvm/Support/MemoryBuffer.h"
31#include "llvm/Support/raw_ostream.h"
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000032
33using namespace clang;
34using llvm::utostr;
35
36namespace {
37 class RewriteModernObjC : public ASTConsumer {
38 protected:
39
40 enum {
41 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
42 block, ... */
43 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
44 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
45 __block variable */
46 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
47 helpers */
48 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
49 support routines */
50 BLOCK_BYREF_CURRENT_MAX = 256
51 };
52
53 enum {
54 BLOCK_NEEDS_FREE = (1 << 24),
55 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
56 BLOCK_HAS_CXX_OBJ = (1 << 26),
57 BLOCK_IS_GC = (1 << 27),
58 BLOCK_IS_GLOBAL = (1 << 28),
59 BLOCK_HAS_DESCRIPTOR = (1 << 29)
60 };
61 static const int OBJC_ABI_VERSION = 7;
62
63 Rewriter Rewrite;
64 DiagnosticsEngine &Diags;
65 const LangOptions &LangOpts;
66 ASTContext *Context;
67 SourceManager *SM;
68 TranslationUnitDecl *TUDecl;
69 FileID MainFileID;
70 const char *MainFileStart, *MainFileEnd;
71 Stmt *CurrentBody;
72 ParentMap *PropParentMap; // created lazily.
73 std::string InFileName;
74 raw_ostream* OutFile;
75 std::string Preamble;
76
77 TypeDecl *ProtocolTypeDecl;
78 VarDecl *GlobalVarDecl;
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +000079 Expr *GlobalConstructionExp;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000080 unsigned RewriteFailedDiag;
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +000081 unsigned GlobalBlockRewriteFailedDiag;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000082 // ObjC string constant support.
83 unsigned NumObjCStringLiterals;
84 VarDecl *ConstantStringClassReference;
85 RecordDecl *NSStringRecord;
86
87 // ObjC foreach break/continue generation support.
88 int BcLabelCount;
89
90 unsigned TryFinallyContainsReturnDiag;
91 // Needed for super.
92 ObjCMethodDecl *CurMethodDef;
93 RecordDecl *SuperStructDecl;
94 RecordDecl *ConstantStringDecl;
95
96 FunctionDecl *MsgSendFunctionDecl;
97 FunctionDecl *MsgSendSuperFunctionDecl;
98 FunctionDecl *MsgSendStretFunctionDecl;
99 FunctionDecl *MsgSendSuperStretFunctionDecl;
100 FunctionDecl *MsgSendFpretFunctionDecl;
101 FunctionDecl *GetClassFunctionDecl;
102 FunctionDecl *GetMetaClassFunctionDecl;
103 FunctionDecl *GetSuperClassFunctionDecl;
104 FunctionDecl *SelGetUidFunctionDecl;
105 FunctionDecl *CFStringFunctionDecl;
106 FunctionDecl *SuperContructorFunctionDecl;
107 FunctionDecl *CurFunctionDef;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000108
109 /* Misc. containers needed for meta-data rewrite. */
110 SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
111 SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
112 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
113 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000114 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCWrittenInterfaces;
Fariborz Jahanian8fba8942012-04-30 23:20:30 +0000115 llvm::SmallPtrSet<TagDecl*, 32> GlobalDefinedTags;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000116 SmallVector<ObjCInterfaceDecl*, 32> ObjCInterfacesSeen;
Fariborz Jahanian88f7f752012-03-14 23:18:19 +0000117 /// DefinedNonLazyClasses - List of defined "non-lazy" classes.
118 SmallVector<ObjCInterfaceDecl*, 8> DefinedNonLazyClasses;
119
120 /// DefinedNonLazyCategories - List of defined "non-lazy" categories.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000121 SmallVector<ObjCCategoryDecl *, 8> DefinedNonLazyCategories;
Fariborz Jahanian88f7f752012-03-14 23:18:19 +0000122
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000123 SmallVector<Stmt *, 32> Stmts;
124 SmallVector<int, 8> ObjCBcLabelNo;
125 // Remember all the @protocol(<expr>) expressions.
126 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
127
128 llvm::DenseSet<uint64_t> CopyDestroyCache;
129
130 // Block expressions.
131 SmallVector<BlockExpr *, 32> Blocks;
132 SmallVector<int, 32> InnerDeclRefsCount;
John McCallf4b88a42012-03-10 09:33:50 +0000133 SmallVector<DeclRefExpr *, 32> InnerDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000134
John McCallf4b88a42012-03-10 09:33:50 +0000135 SmallVector<DeclRefExpr *, 32> BlockDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000136
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +0000137
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000138 // Block related declarations.
139 SmallVector<ValueDecl *, 8> BlockByCopyDecls;
140 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
141 SmallVector<ValueDecl *, 8> BlockByRefDecls;
142 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
143 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
144 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
145 llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
146
147 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
Fariborz Jahanian72c88f12012-02-22 18:13:25 +0000148 llvm::DenseMap<ObjCInterfaceDecl *,
149 llvm::SmallPtrSet<ObjCIvarDecl *, 8> > ReferencedIvars;
150
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +0000151 // ivar bitfield grouping containers
152 llvm::DenseSet<const ObjCInterfaceDecl *> ObjCInterefaceHasBitfieldGroups;
153 llvm::DenseMap<const ObjCIvarDecl* , unsigned> IvarGroupNumber;
154 // This container maps an <class, group number for ivar> tuple to the type
155 // of the struct where the bitfield belongs.
156 llvm::DenseMap<std::pair<const ObjCInterfaceDecl*, unsigned>, QualType> GroupRecordType;
Fariborz Jahanian31c4a4b2013-02-07 22:50:40 +0000157 SmallVector<FunctionDecl*, 32> FunctionDefinitionsSeen;
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +0000158
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000159 // This maps an original source AST to it's rewritten form. This allows
160 // us to avoid rewriting the same node twice (which is very uncommon).
161 // This is needed to support some of the exotic property rewriting.
162 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
163
164 // Needed for header files being rewritten
165 bool IsHeader;
166 bool SilenceRewriteMacroWarning;
Fariborz Jahanianada71912013-02-08 00:27:34 +0000167 bool GenerateLineInfo;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000168 bool objc_impl_method;
169
170 bool DisableReplaceStmt;
171 class DisableReplaceStmtScope {
172 RewriteModernObjC &R;
173 bool SavedValue;
174
175 public:
176 DisableReplaceStmtScope(RewriteModernObjC &R)
177 : R(R), SavedValue(R.DisableReplaceStmt) {
178 R.DisableReplaceStmt = true;
179 }
180 ~DisableReplaceStmtScope() {
181 R.DisableReplaceStmt = SavedValue;
182 }
183 };
184 void InitializeCommon(ASTContext &context);
185
186 public:
Fariborz Jahanian90af4e22012-02-14 17:19:02 +0000187 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000188 // Top Level Driver code.
189 virtual bool HandleTopLevelDecl(DeclGroupRef D) {
190 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
191 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*I)) {
192 if (!Class->isThisDeclarationADefinition()) {
193 RewriteForwardClassDecl(D);
194 break;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000195 } else {
196 // Keep track of all interface declarations seen.
Fariborz Jahanianf3295272012-02-24 21:42:38 +0000197 ObjCInterfacesSeen.push_back(Class);
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000198 break;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000199 }
200 }
201
202 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*I)) {
203 if (!Proto->isThisDeclarationADefinition()) {
204 RewriteForwardProtocolDecl(D);
205 break;
206 }
207 }
208
Fariborz Jahanian31c4a4b2013-02-07 22:50:40 +0000209 if (FunctionDecl *FDecl = dyn_cast<FunctionDecl>(*I)) {
210 // Under modern abi, we cannot translate body of the function
211 // yet until all class extensions and its implementation is seen.
212 // This is because they may introduce new bitfields which must go
213 // into their grouping struct.
214 if (FDecl->isThisDeclarationADefinition() &&
215 // Not c functions defined inside an objc container.
216 !FDecl->isTopLevelDeclInObjCContainer()) {
217 FunctionDefinitionsSeen.push_back(FDecl);
218 break;
219 }
220 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000221 HandleTopLevelSingleDecl(*I);
222 }
223 return true;
224 }
225 void HandleTopLevelSingleDecl(Decl *D);
226 void HandleDeclInMainFile(Decl *D);
227 RewriteModernObjC(std::string inFile, raw_ostream *OS,
228 DiagnosticsEngine &D, const LangOptions &LOpts,
Fariborz Jahanianada71912013-02-08 00:27:34 +0000229 bool silenceMacroWarn, bool LineInfo);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000230
231 ~RewriteModernObjC() {}
232
233 virtual void HandleTranslationUnit(ASTContext &C);
234
235 void ReplaceStmt(Stmt *Old, Stmt *New) {
236 Stmt *ReplacingStmt = ReplacedNodes[Old];
237
238 if (ReplacingStmt)
239 return; // We can't rewrite the same node twice.
240
241 if (DisableReplaceStmt)
242 return;
243
244 // If replacement succeeded or warning disabled return with no warning.
245 if (!Rewrite.ReplaceStmt(Old, New)) {
246 ReplacedNodes[Old] = New;
247 return;
248 }
249 if (SilenceRewriteMacroWarning)
250 return;
251 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
252 << Old->getSourceRange();
253 }
254
255 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
256 if (DisableReplaceStmt)
257 return;
258
259 // Measure the old text.
260 int Size = Rewrite.getRangeSize(SrcRange);
261 if (Size == -1) {
262 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
263 << Old->getSourceRange();
264 return;
265 }
266 // Get the new text.
267 std::string SStr;
268 llvm::raw_string_ostream S(SStr);
Richard Smithd1420c62012-08-16 03:56:14 +0000269 New->printPretty(S, 0, PrintingPolicy(LangOpts));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000270 const std::string &Str = S.str();
271
272 // If replacement succeeded or warning disabled return with no warning.
273 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
274 ReplacedNodes[Old] = New;
275 return;
276 }
277 if (SilenceRewriteMacroWarning)
278 return;
279 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
280 << Old->getSourceRange();
281 }
282
283 void InsertText(SourceLocation Loc, StringRef Str,
284 bool InsertAfter = true) {
285 // If insertion succeeded or warning disabled return with no warning.
286 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
287 SilenceRewriteMacroWarning)
288 return;
289
290 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
291 }
292
293 void ReplaceText(SourceLocation Start, unsigned OrigLength,
294 StringRef Str) {
295 // If removal succeeded or warning disabled return with no warning.
296 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
297 SilenceRewriteMacroWarning)
298 return;
299
300 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
301 }
302
303 // Syntactic Rewriting.
304 void RewriteRecordBody(RecordDecl *RD);
305 void RewriteInclude();
Fariborz Jahanian96205962012-11-06 17:30:23 +0000306 void RewriteLineDirective(const Decl *D);
Fariborz Jahanianf616ae22012-11-06 23:25:49 +0000307 void ConvertSourceLocationToLineDirective(SourceLocation Loc,
308 std::string &LineString);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000309 void RewriteForwardClassDecl(DeclGroupRef D);
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000310 void RewriteForwardClassDecl(const SmallVector<Decl *, 8> &DG);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000311 void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
312 const std::string &typedefString);
313 void RewriteImplementations();
314 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
315 ObjCImplementationDecl *IMD,
316 ObjCCategoryImplDecl *CID);
317 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
318 void RewriteImplementationDecl(Decl *Dcl);
319 void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
320 ObjCMethodDecl *MDecl, std::string &ResultStr);
321 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
322 const FunctionType *&FPRetType);
323 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
324 ValueDecl *VD, bool def=false);
325 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
326 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
327 void RewriteForwardProtocolDecl(DeclGroupRef D);
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000328 void RewriteForwardProtocolDecl(const SmallVector<Decl *, 8> &DG);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000329 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
330 void RewriteProperty(ObjCPropertyDecl *prop);
331 void RewriteFunctionDecl(FunctionDecl *FD);
332 void RewriteBlockPointerType(std::string& Str, QualType Type);
333 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +0000334 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000335 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
336 void RewriteTypeOfDecl(VarDecl *VD);
337 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +0000338
339 std::string getIvarAccessString(ObjCIvarDecl *D);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000340
341 // Expression Rewriting.
342 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
343 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
344 Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
345 Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
346 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
347 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
348 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian55947042012-03-27 20:17:30 +0000349 Stmt *RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp);
Patrick Beardeb382ec2012-04-19 00:25:12 +0000350 Stmt *RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp);
Fariborz Jahanian86cff602012-03-30 23:35:47 +0000351 Stmt *RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +0000352 Stmt *RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000353 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000354 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahanian042b91d2012-05-23 23:47:20 +0000355 Stmt *RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000356 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
357 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
358 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
359 SourceLocation OrigEnd);
360 Stmt *RewriteBreakStmt(BreakStmt *S);
361 Stmt *RewriteContinueStmt(ContinueStmt *S);
362 void RewriteCastExpr(CStyleCastExpr *CE);
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +0000363 void RewriteImplicitCastObjCExpr(CastExpr *IE);
Fariborz Jahanianb3f904f2012-04-03 17:35:38 +0000364 void RewriteLinkageSpec(LinkageSpecDecl *LSD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000365
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +0000366 // Computes ivar bitfield group no.
367 unsigned ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV);
368 // Names field decl. for ivar bitfield group.
369 void ObjCIvarBitfieldGroupDecl(ObjCIvarDecl *IV, std::string &Result);
370 // Names struct type for ivar bitfield group.
371 void ObjCIvarBitfieldGroupType(ObjCIvarDecl *IV, std::string &Result);
372 // Names symbol for ivar bitfield group field offset.
373 void ObjCIvarBitfieldGroupOffset(ObjCIvarDecl *IV, std::string &Result);
374 // Given an ivar bitfield, it builds (or finds) its group record type.
375 QualType GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl *IV);
376 QualType SynthesizeBitfieldGroupStructType(
377 ObjCIvarDecl *IV,
378 SmallVectorImpl<ObjCIvarDecl *> &IVars);
379
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000380 // Block rewriting.
381 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
382
383 // Block specific rewrite rules.
384 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +0000385 void RewriteByRefVar(VarDecl *VD, bool firstDecl, bool lastDecl);
John McCallf4b88a42012-03-10 09:33:50 +0000386 Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000387 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
388 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
389
390 void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
391 std::string &Result);
392
Fariborz Jahanian15f87772012-02-28 22:45:07 +0000393 void RewriteObjCFieldDecl(FieldDecl *fieldDecl, std::string &Result);
Fariborz Jahanianb68258f2012-05-01 17:46:45 +0000394 bool IsTagDefinedInsideClass(ObjCContainerDecl *IDecl, TagDecl *Tag,
Fariborz Jahanian8fba8942012-04-30 23:20:30 +0000395 bool &IsNamedDefinition);
396 void RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
397 std::string &Result);
Fariborz Jahanian15f87772012-02-28 22:45:07 +0000398
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +0000399 bool RewriteObjCFieldDeclType(QualType &Type, std::string &Result);
400
Fariborz Jahanian72c88f12012-02-22 18:13:25 +0000401 void RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
402 std::string &Result);
403
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000404 virtual void Initialize(ASTContext &context);
405
Benjamin Kramer48d798c2012-06-02 10:20:41 +0000406 // Misc. AST transformation routines. Sometimes they end up calling
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000407 // rewriting routines on the new ASTs.
408 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
409 Expr **args, unsigned nargs,
410 SourceLocation StartLoc=SourceLocation(),
411 SourceLocation EndLoc=SourceLocation());
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +0000412
413 Expr *SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
414 QualType msgSendType,
415 QualType returnType,
416 SmallVectorImpl<QualType> &ArgTypes,
417 SmallVectorImpl<Expr*> &MsgExprs,
418 ObjCMethodDecl *Method);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000419
420 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
421 SourceLocation StartLoc=SourceLocation(),
422 SourceLocation EndLoc=SourceLocation());
423
424 void SynthCountByEnumWithState(std::string &buf);
425 void SynthMsgSendFunctionDecl();
426 void SynthMsgSendSuperFunctionDecl();
427 void SynthMsgSendStretFunctionDecl();
428 void SynthMsgSendFpretFunctionDecl();
429 void SynthMsgSendSuperStretFunctionDecl();
430 void SynthGetClassFunctionDecl();
431 void SynthGetMetaClassFunctionDecl();
432 void SynthGetSuperClassFunctionDecl();
433 void SynthSelGetUidFunctionDecl();
434 void SynthSuperContructorFunctionDecl();
435
436 // Rewriting metadata
437 template<typename MethodIterator>
438 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
439 MethodIterator MethodEnd,
440 bool IsInstanceMethod,
441 StringRef prefix,
442 StringRef ClassName,
443 std::string &Result);
Fariborz Jahanianda9624a2012-02-08 19:53:58 +0000444 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
445 std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000446 void RewriteObjCProtocolListMetaData(
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000447 const ObjCList<ObjCProtocolDecl> &Prots,
448 StringRef prefix, StringRef ClassName, std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000449 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000450 std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000451 void RewriteClassSetupInitHook(std::string &Result);
Fariborz Jahaniane0335782012-03-27 18:41:05 +0000452
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000453 void RewriteMetaDataIntoBuffer(std::string &Result);
454 void WriteImageInfo(std::string &Result);
455 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000456 std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000457 void RewriteCategorySetupInitHook(std::string &Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000458
459 // Rewriting ivar
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000460 void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000461 std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000462 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000463
464
465 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
466 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
467 StringRef funcName, std::string Tag);
468 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
469 StringRef funcName, std::string Tag);
470 std::string SynthesizeBlockImpl(BlockExpr *CE,
471 std::string Tag, std::string Desc);
472 std::string SynthesizeBlockDescriptor(std::string DescTag,
473 std::string ImplTag,
474 int i, StringRef funcName,
475 unsigned hasCopy);
476 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
477 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
478 StringRef FunName);
479 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
480 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
John McCallf4b88a42012-03-10 09:33:50 +0000481 const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000482
483 // Misc. helper routines.
484 QualType getProtocolType();
485 void WarnAboutReturnGotoStmts(Stmt *S);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000486 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
487 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
488 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
489
490 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
491 void CollectBlockDeclRefInfo(BlockExpr *Exp);
492 void GetBlockDeclRefExprs(Stmt *S);
493 void GetInnerBlockDeclRefExprs(Stmt *S,
John McCallf4b88a42012-03-10 09:33:50 +0000494 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000495 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
496
497 // We avoid calling Type::isBlockPointerType(), since it operates on the
498 // canonical type. We only care if the top-level type is a closure pointer.
499 bool isTopLevelBlockPointerType(QualType T) {
500 return isa<BlockPointerType>(T);
501 }
502
503 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
504 /// to a function pointer type and upon success, returns true; false
505 /// otherwise.
506 bool convertBlockPointerToFunctionPointer(QualType &T) {
507 if (isTopLevelBlockPointerType(T)) {
508 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
509 T = Context->getPointerType(BPT->getPointeeType());
510 return true;
511 }
512 return false;
513 }
514
Fariborz Jahanian164d6f82012-02-13 18:57:49 +0000515 bool convertObjCTypeToCStyleType(QualType &T);
516
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000517 bool needToScanForQualifiers(QualType T);
518 QualType getSuperStructType();
519 QualType getConstantStringStructType();
520 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
521 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
522
523 void convertToUnqualifiedObjCType(QualType &T) {
Fariborz Jahaniane35abe12012-04-06 22:29:36 +0000524 if (T->isObjCQualifiedIdType()) {
525 bool isConst = T.isConstQualified();
526 T = isConst ? Context->getObjCIdType().withConst()
527 : Context->getObjCIdType();
528 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000529 else if (T->isObjCQualifiedClassType())
530 T = Context->getObjCClassType();
531 else if (T->isObjCObjectPointerType() &&
532 T->getPointeeType()->isObjCQualifiedInterfaceType()) {
533 if (const ObjCObjectPointerType * OBJPT =
534 T->getAsObjCInterfacePointerType()) {
535 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
536 T = QualType(IFaceT, 0);
537 T = Context->getPointerType(T);
538 }
539 }
540 }
541
542 // FIXME: This predicate seems like it would be useful to add to ASTContext.
543 bool isObjCType(QualType T) {
544 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
545 return false;
546
547 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
548
549 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
550 OCT == Context->getCanonicalType(Context->getObjCClassType()))
551 return true;
552
553 if (const PointerType *PT = OCT->getAs<PointerType>()) {
554 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
555 PT->getPointeeType()->isObjCQualifiedIdType())
556 return true;
557 }
558 return false;
559 }
560 bool PointerTypeTakesAnyBlockArguments(QualType QT);
561 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
562 void GetExtentOfArgList(const char *Name, const char *&LParen,
563 const char *&RParen);
564
565 void QuoteDoublequotes(std::string &From, std::string &To) {
566 for (unsigned i = 0; i < From.length(); i++) {
567 if (From[i] == '"')
568 To += "\\\"";
569 else
570 To += From[i];
571 }
572 }
573
574 QualType getSimpleFunctionType(QualType result,
Jordan Rosebea522f2013-03-08 21:51:21 +0000575 ArrayRef<QualType> args,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000576 bool variadic = false) {
577 if (result == Context->getObjCInstanceType())
578 result = Context->getObjCIdType();
579 FunctionProtoType::ExtProtoInfo fpi;
580 fpi.Variadic = variadic;
Jordan Rosebea522f2013-03-08 21:51:21 +0000581 return Context->getFunctionType(result, args, fpi);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000582 }
583
584 // Helper function: create a CStyleCastExpr with trivial type source info.
585 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
586 CastKind Kind, Expr *E) {
587 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
588 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, 0, TInfo,
589 SourceLocation(), SourceLocation());
590 }
Fariborz Jahanian88f7f752012-03-14 23:18:19 +0000591
592 bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const {
593 IdentifierInfo* II = &Context->Idents.get("load");
594 Selector LoadSel = Context->Selectors.getSelector(0, &II);
595 return OD->getClassMethod(LoadSel) != 0;
596 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000597 };
598
599}
600
601void RewriteModernObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
602 NamedDecl *D) {
603 if (const FunctionProtoType *fproto
604 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
605 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
606 E = fproto->arg_type_end(); I && (I != E); ++I)
607 if (isTopLevelBlockPointerType(*I)) {
608 // All the args are checked/rewritten. Don't call twice!
609 RewriteBlockPointerDecl(D);
610 break;
611 }
612 }
613}
614
615void RewriteModernObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
616 const PointerType *PT = funcType->getAs<PointerType>();
617 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
618 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
619}
620
621static bool IsHeaderFile(const std::string &Filename) {
622 std::string::size_type DotPos = Filename.rfind('.');
623
624 if (DotPos == std::string::npos) {
625 // no file extension
626 return false;
627 }
628
629 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
630 // C header: .h
631 // C++ header: .hh or .H;
632 return Ext == "h" || Ext == "hh" || Ext == "H";
633}
634
635RewriteModernObjC::RewriteModernObjC(std::string inFile, raw_ostream* OS,
636 DiagnosticsEngine &D, const LangOptions &LOpts,
Fariborz Jahanianada71912013-02-08 00:27:34 +0000637 bool silenceMacroWarn,
638 bool LineInfo)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000639 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
Fariborz Jahanianada71912013-02-08 00:27:34 +0000640 SilenceRewriteMacroWarning(silenceMacroWarn), GenerateLineInfo(LineInfo) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000641 IsHeader = IsHeaderFile(inFile);
642 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
643 "rewriting sub-expression within a macro (may not be correct)");
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +0000644 // FIXME. This should be an error. But if block is not called, it is OK. And it
645 // may break including some headers.
646 GlobalBlockRewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
647 "rewriting block literal declared in global scope is not implemented");
648
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000649 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
650 DiagnosticsEngine::Warning,
651 "rewriter doesn't support user-specified control flow semantics "
652 "for @try/@finally (code may not execute properly)");
653}
654
655ASTConsumer *clang::CreateModernObjCRewriter(const std::string& InFile,
656 raw_ostream* OS,
657 DiagnosticsEngine &Diags,
658 const LangOptions &LOpts,
Fariborz Jahanianada71912013-02-08 00:27:34 +0000659 bool SilenceRewriteMacroWarning,
660 bool LineInfo) {
661 return new RewriteModernObjC(InFile, OS, Diags, LOpts,
662 SilenceRewriteMacroWarning, LineInfo);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000663}
664
665void RewriteModernObjC::InitializeCommon(ASTContext &context) {
666 Context = &context;
667 SM = &Context->getSourceManager();
668 TUDecl = Context->getTranslationUnitDecl();
669 MsgSendFunctionDecl = 0;
670 MsgSendSuperFunctionDecl = 0;
671 MsgSendStretFunctionDecl = 0;
672 MsgSendSuperStretFunctionDecl = 0;
673 MsgSendFpretFunctionDecl = 0;
674 GetClassFunctionDecl = 0;
675 GetMetaClassFunctionDecl = 0;
676 GetSuperClassFunctionDecl = 0;
677 SelGetUidFunctionDecl = 0;
678 CFStringFunctionDecl = 0;
679 ConstantStringClassReference = 0;
680 NSStringRecord = 0;
681 CurMethodDef = 0;
682 CurFunctionDef = 0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000683 GlobalVarDecl = 0;
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +0000684 GlobalConstructionExp = 0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000685 SuperStructDecl = 0;
686 ProtocolTypeDecl = 0;
687 ConstantStringDecl = 0;
688 BcLabelCount = 0;
689 SuperContructorFunctionDecl = 0;
690 NumObjCStringLiterals = 0;
691 PropParentMap = 0;
692 CurrentBody = 0;
693 DisableReplaceStmt = false;
694 objc_impl_method = false;
695
696 // Get the ID and start/end of the main file.
697 MainFileID = SM->getMainFileID();
698 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
699 MainFileStart = MainBuf->getBufferStart();
700 MainFileEnd = MainBuf->getBufferEnd();
701
David Blaikie4e4d0842012-03-11 07:00:24 +0000702 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000703}
704
705//===----------------------------------------------------------------------===//
706// Top Level Driver Code
707//===----------------------------------------------------------------------===//
708
709void RewriteModernObjC::HandleTopLevelSingleDecl(Decl *D) {
710 if (Diags.hasErrorOccurred())
711 return;
712
713 // Two cases: either the decl could be in the main file, or it could be in a
714 // #included file. If the former, rewrite it now. If the later, check to see
715 // if we rewrote the #include/#import.
716 SourceLocation Loc = D->getLocation();
717 Loc = SM->getExpansionLoc(Loc);
718
719 // If this is for a builtin, ignore it.
720 if (Loc.isInvalid()) return;
721
722 // Look for built-in declarations that we need to refer during the rewrite.
723 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
724 RewriteFunctionDecl(FD);
725 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
726 // declared in <Foundation/NSString.h>
727 if (FVD->getName() == "_NSConstantStringClassReference") {
728 ConstantStringClassReference = FVD;
729 return;
730 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000731 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
732 RewriteCategoryDecl(CD);
733 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
734 if (PD->isThisDeclarationADefinition())
735 RewriteProtocolDecl(PD);
736 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
Fariborz Jahanian8e86b2d2012-04-04 17:16:15 +0000737 // FIXME. This will not work in all situations and leaving it out
738 // is harmless.
739 // RewriteLinkageSpec(LSD);
740
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000741 // Recurse into linkage specifications
742 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
743 DIEnd = LSD->decls_end();
744 DI != DIEnd; ) {
745 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
746 if (!IFace->isThisDeclarationADefinition()) {
747 SmallVector<Decl *, 8> DG;
748 SourceLocation StartLoc = IFace->getLocStart();
749 do {
750 if (isa<ObjCInterfaceDecl>(*DI) &&
751 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
752 StartLoc == (*DI)->getLocStart())
753 DG.push_back(*DI);
754 else
755 break;
756
757 ++DI;
758 } while (DI != DIEnd);
759 RewriteForwardClassDecl(DG);
760 continue;
761 }
Fariborz Jahanianb3f904f2012-04-03 17:35:38 +0000762 else {
763 // Keep track of all interface declarations seen.
764 ObjCInterfacesSeen.push_back(IFace);
765 ++DI;
766 continue;
767 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000768 }
769
770 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
771 if (!Proto->isThisDeclarationADefinition()) {
772 SmallVector<Decl *, 8> DG;
773 SourceLocation StartLoc = Proto->getLocStart();
774 do {
775 if (isa<ObjCProtocolDecl>(*DI) &&
776 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
777 StartLoc == (*DI)->getLocStart())
778 DG.push_back(*DI);
779 else
780 break;
781
782 ++DI;
783 } while (DI != DIEnd);
784 RewriteForwardProtocolDecl(DG);
785 continue;
786 }
787 }
788
789 HandleTopLevelSingleDecl(*DI);
790 ++DI;
791 }
792 }
793 // If we have a decl in the main file, see if we should rewrite it.
794 if (SM->isFromMainFile(Loc))
795 return HandleDeclInMainFile(D);
796}
797
798//===----------------------------------------------------------------------===//
799// Syntactic (non-AST) Rewriting Code
800//===----------------------------------------------------------------------===//
801
802void RewriteModernObjC::RewriteInclude() {
803 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
804 StringRef MainBuf = SM->getBufferData(MainFileID);
805 const char *MainBufStart = MainBuf.begin();
806 const char *MainBufEnd = MainBuf.end();
807 size_t ImportLen = strlen("import");
808
809 // Loop over the whole file, looking for includes.
810 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
811 if (*BufPtr == '#') {
812 if (++BufPtr == MainBufEnd)
813 return;
814 while (*BufPtr == ' ' || *BufPtr == '\t')
815 if (++BufPtr == MainBufEnd)
816 return;
817 if (!strncmp(BufPtr, "import", ImportLen)) {
818 // replace import with include
819 SourceLocation ImportLoc =
820 LocStart.getLocWithOffset(BufPtr-MainBufStart);
821 ReplaceText(ImportLoc, ImportLen, "include");
822 BufPtr += ImportLen;
823 }
824 }
825 }
826}
827
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +0000828static void WriteInternalIvarName(const ObjCInterfaceDecl *IDecl,
829 ObjCIvarDecl *IvarDecl, std::string &Result) {
830 Result += "OBJC_IVAR_$_";
831 Result += IDecl->getName();
832 Result += "$";
833 Result += IvarDecl->getName();
834}
835
836std::string
837RewriteModernObjC::getIvarAccessString(ObjCIvarDecl *D) {
838 const ObjCInterfaceDecl *ClassDecl = D->getContainingInterface();
839
840 // Build name of symbol holding ivar offset.
841 std::string IvarOffsetName;
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +0000842 if (D->isBitField())
843 ObjCIvarBitfieldGroupOffset(D, IvarOffsetName);
844 else
845 WriteInternalIvarName(ClassDecl, D, IvarOffsetName);
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +0000846
847
848 std::string S = "(*(";
849 QualType IvarT = D->getType();
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +0000850 if (D->isBitField())
851 IvarT = GetGroupRecordTypeForObjCIvarBitfield(D);
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +0000852
853 if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
854 RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
855 RD = RD->getDefinition();
856 if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
857 // decltype(((Foo_IMPL*)0)->bar) *
858 ObjCContainerDecl *CDecl =
859 dyn_cast<ObjCContainerDecl>(D->getDeclContext());
860 // ivar in class extensions requires special treatment.
861 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
862 CDecl = CatDecl->getClassInterface();
863 std::string RecName = CDecl->getName();
864 RecName += "_IMPL";
865 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
866 SourceLocation(), SourceLocation(),
867 &Context->Idents.get(RecName.c_str()));
868 QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
869 unsigned UnsignedIntSize =
870 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
871 Expr *Zero = IntegerLiteral::Create(*Context,
872 llvm::APInt(UnsignedIntSize, 0),
873 Context->UnsignedIntTy, SourceLocation());
874 Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
875 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
876 Zero);
877 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
878 SourceLocation(),
879 &Context->Idents.get(D->getNameAsString()),
880 IvarT, 0,
881 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +0000882 ICIS_NoInit);
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +0000883 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
884 FD->getType(), VK_LValue,
885 OK_Ordinary);
886 IvarT = Context->getDecltypeType(ME, ME->getType());
887 }
888 }
889 convertObjCTypeToCStyleType(IvarT);
890 QualType castT = Context->getPointerType(IvarT);
891 std::string TypeString(castT.getAsString(Context->getPrintingPolicy()));
892 S += TypeString;
893 S += ")";
894
895 // ((char *)self + IVAR_OFFSET_SYMBOL_NAME)
896 S += "((char *)self + ";
897 S += IvarOffsetName;
898 S += "))";
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +0000899 if (D->isBitField()) {
900 S += ".";
901 S += D->getNameAsString();
902 }
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +0000903 ReferencedIvars[const_cast<ObjCInterfaceDecl *>(ClassDecl)].insert(D);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000904 return S;
905}
906
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000907/// mustSynthesizeSetterGetterMethod - returns true if setter or getter has not
908/// been found in the class implementation. In this case, it must be synthesized.
909static bool mustSynthesizeSetterGetterMethod(ObjCImplementationDecl *IMP,
910 ObjCPropertyDecl *PD,
911 bool getter) {
912 return getter ? !IMP->getInstanceMethod(PD->getGetterName())
913 : !IMP->getInstanceMethod(PD->getSetterName());
914
915}
916
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000917void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
918 ObjCImplementationDecl *IMD,
919 ObjCCategoryImplDecl *CID) {
920 static bool objcGetPropertyDefined = false;
921 static bool objcSetPropertyDefined = false;
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000922 SourceLocation startGetterSetterLoc;
923
924 if (PID->getLocStart().isValid()) {
925 SourceLocation startLoc = PID->getLocStart();
926 InsertText(startLoc, "// ");
927 const char *startBuf = SM->getCharacterData(startLoc);
928 assert((*startBuf == '@') && "bogus @synthesize location");
929 const char *semiBuf = strchr(startBuf, ';');
930 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
931 startGetterSetterLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
932 }
933 else
934 startGetterSetterLoc = IMD ? IMD->getLocEnd() : CID->getLocEnd();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000935
936 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
937 return; // FIXME: is this correct?
938
939 // Generate the 'getter' function.
940 ObjCPropertyDecl *PD = PID->getPropertyDecl();
941 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Jordan Rose62bbe072013-03-15 21:41:35 +0000942 assert(IMD && OID && "Synthesized ivars must be attached to @implementation");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000943
Bill Wendlingad017fa2012-12-20 19:22:21 +0000944 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000945 if (mustSynthesizeSetterGetterMethod(IMD, PD, true /*getter*/)) {
Bill Wendlingad017fa2012-12-20 19:22:21 +0000946 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
947 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000948 ObjCPropertyDecl::OBJC_PR_copy));
949 std::string Getr;
950 if (GenGetProperty && !objcGetPropertyDefined) {
951 objcGetPropertyDefined = true;
952 // FIXME. Is this attribute correct in all cases?
953 Getr = "\nextern \"C\" __declspec(dllimport) "
954 "id objc_getProperty(id, SEL, long, bool);\n";
955 }
956 RewriteObjCMethodDecl(OID->getContainingInterface(),
957 PD->getGetterMethodDecl(), Getr);
958 Getr += "{ ";
959 // Synthesize an explicit cast to gain access to the ivar.
960 // See objc-act.c:objc_synthesize_new_getter() for details.
961 if (GenGetProperty) {
962 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
963 Getr += "typedef ";
964 const FunctionType *FPRetType = 0;
965 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
966 FPRetType);
967 Getr += " _TYPE";
968 if (FPRetType) {
969 Getr += ")"; // close the precedence "scope" for "*".
970
971 // Now, emit the argument types (if any).
972 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
973 Getr += "(";
974 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
975 if (i) Getr += ", ";
976 std::string ParamStr = FT->getArgType(i).getAsString(
977 Context->getPrintingPolicy());
978 Getr += ParamStr;
979 }
980 if (FT->isVariadic()) {
981 if (FT->getNumArgs()) Getr += ", ";
982 Getr += "...";
983 }
984 Getr += ")";
985 } else
986 Getr += "()";
987 }
988 Getr += ";\n";
989 Getr += "return (_TYPE)";
990 Getr += "objc_getProperty(self, _cmd, ";
991 RewriteIvarOffsetComputation(OID, Getr);
992 Getr += ", 1)";
993 }
994 else
995 Getr += "return " + getIvarAccessString(OID);
996 Getr += "; }";
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000997 InsertText(startGetterSetterLoc, Getr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000998 }
999
Fariborz Jahanian301e2e42012-05-03 22:52:13 +00001000 if (PD->isReadOnly() ||
1001 !mustSynthesizeSetterGetterMethod(IMD, PD, false /*setter*/))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001002 return;
1003
1004 // Generate the 'setter' function.
1005 std::string Setr;
Bill Wendlingad017fa2012-12-20 19:22:21 +00001006 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001007 ObjCPropertyDecl::OBJC_PR_copy);
1008 if (GenSetProperty && !objcSetPropertyDefined) {
1009 objcSetPropertyDefined = true;
1010 // FIXME. Is this attribute correct in all cases?
1011 Setr = "\nextern \"C\" __declspec(dllimport) "
1012 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
1013 }
1014
1015 RewriteObjCMethodDecl(OID->getContainingInterface(),
1016 PD->getSetterMethodDecl(), Setr);
1017 Setr += "{ ";
1018 // Synthesize an explicit cast to initialize the ivar.
1019 // See objc-act.c:objc_synthesize_new_setter() for details.
1020 if (GenSetProperty) {
1021 Setr += "objc_setProperty (self, _cmd, ";
1022 RewriteIvarOffsetComputation(OID, Setr);
1023 Setr += ", (id)";
1024 Setr += PD->getName();
1025 Setr += ", ";
Bill Wendlingad017fa2012-12-20 19:22:21 +00001026 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001027 Setr += "0, ";
1028 else
1029 Setr += "1, ";
Bill Wendlingad017fa2012-12-20 19:22:21 +00001030 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001031 Setr += "1)";
1032 else
1033 Setr += "0)";
1034 }
1035 else {
1036 Setr += getIvarAccessString(OID) + " = ";
1037 Setr += PD->getName();
1038 }
Fariborz Jahanian301e2e42012-05-03 22:52:13 +00001039 Setr += "; }\n";
1040 InsertText(startGetterSetterLoc, Setr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001041}
1042
1043static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
1044 std::string &typedefString) {
Fariborz Jahanianbfaa1112013-02-08 17:15:07 +00001045 typedefString += "\n#ifndef _REWRITER_typedef_";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001046 typedefString += ForwardDecl->getNameAsString();
1047 typedefString += "\n";
1048 typedefString += "#define _REWRITER_typedef_";
1049 typedefString += ForwardDecl->getNameAsString();
1050 typedefString += "\n";
1051 typedefString += "typedef struct objc_object ";
1052 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001053 // typedef struct { } _objc_exc_Classname;
1054 typedefString += ";\ntypedef struct {} _objc_exc_";
1055 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001056 typedefString += ";\n#endif\n";
1057}
1058
1059void RewriteModernObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
1060 const std::string &typedefString) {
1061 SourceLocation startLoc = ClassDecl->getLocStart();
1062 const char *startBuf = SM->getCharacterData(startLoc);
1063 const char *semiPtr = strchr(startBuf, ';');
1064 // Replace the @class with typedefs corresponding to the classes.
1065 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
1066}
1067
1068void RewriteModernObjC::RewriteForwardClassDecl(DeclGroupRef D) {
1069 std::string typedefString;
1070 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
1071 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(*I);
1072 if (I == D.begin()) {
1073 // Translate to typedef's that forward reference structs with the same name
1074 // as the class. As a convenience, we include the original declaration
1075 // as a comment.
1076 typedefString += "// @class ";
1077 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanianbfaa1112013-02-08 17:15:07 +00001078 typedefString += ";";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001079 }
1080 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
1081 }
1082 DeclGroupRef::iterator I = D.begin();
1083 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
1084}
1085
1086void RewriteModernObjC::RewriteForwardClassDecl(
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001087 const SmallVector<Decl *, 8> &D) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001088 std::string typedefString;
1089 for (unsigned i = 0; i < D.size(); i++) {
1090 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
1091 if (i == 0) {
1092 typedefString += "// @class ";
1093 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanianbfaa1112013-02-08 17:15:07 +00001094 typedefString += ";";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001095 }
1096 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
1097 }
1098 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
1099}
1100
1101void RewriteModernObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
1102 // When method is a synthesized one, such as a getter/setter there is
1103 // nothing to rewrite.
1104 if (Method->isImplicit())
1105 return;
1106 SourceLocation LocStart = Method->getLocStart();
1107 SourceLocation LocEnd = Method->getLocEnd();
1108
1109 if (SM->getExpansionLineNumber(LocEnd) >
1110 SM->getExpansionLineNumber(LocStart)) {
1111 InsertText(LocStart, "#if 0\n");
1112 ReplaceText(LocEnd, 1, ";\n#endif\n");
1113 } else {
1114 InsertText(LocStart, "// ");
1115 }
1116}
1117
1118void RewriteModernObjC::RewriteProperty(ObjCPropertyDecl *prop) {
1119 SourceLocation Loc = prop->getAtLoc();
1120
1121 ReplaceText(Loc, 0, "// ");
1122 // FIXME: handle properties that are declared across multiple lines.
1123}
1124
1125void RewriteModernObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
1126 SourceLocation LocStart = CatDecl->getLocStart();
1127
1128 // FIXME: handle category headers that are declared across multiple lines.
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00001129 if (CatDecl->getIvarRBraceLoc().isValid()) {
1130 ReplaceText(LocStart, 1, "/** ");
1131 ReplaceText(CatDecl->getIvarRBraceLoc(), 1, "**/ ");
1132 }
1133 else {
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001134 ReplaceText(LocStart, 0, "// ");
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00001135 }
Fariborz Jahanianaf300292012-02-20 20:09:20 +00001136
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001137 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
1138 E = CatDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001139 RewriteProperty(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001140
1141 for (ObjCCategoryDecl::instmeth_iterator
1142 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
1143 I != E; ++I)
1144 RewriteMethodDeclaration(*I);
1145 for (ObjCCategoryDecl::classmeth_iterator
1146 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
1147 I != E; ++I)
1148 RewriteMethodDeclaration(*I);
1149
1150 // Lastly, comment out the @end.
1151 ReplaceText(CatDecl->getAtEndRange().getBegin(),
1152 strlen("@end"), "/* @end */");
1153}
1154
1155void RewriteModernObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
1156 SourceLocation LocStart = PDecl->getLocStart();
1157 assert(PDecl->isThisDeclarationADefinition());
1158
1159 // FIXME: handle protocol headers that are declared across multiple lines.
1160 ReplaceText(LocStart, 0, "// ");
1161
1162 for (ObjCProtocolDecl::instmeth_iterator
1163 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
1164 I != E; ++I)
1165 RewriteMethodDeclaration(*I);
1166 for (ObjCProtocolDecl::classmeth_iterator
1167 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
1168 I != E; ++I)
1169 RewriteMethodDeclaration(*I);
1170
1171 for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
1172 E = PDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001173 RewriteProperty(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001174
1175 // Lastly, comment out the @end.
1176 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
1177 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
1178
1179 // Must comment out @optional/@required
1180 const char *startBuf = SM->getCharacterData(LocStart);
1181 const char *endBuf = SM->getCharacterData(LocEnd);
1182 for (const char *p = startBuf; p < endBuf; p++) {
1183 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
1184 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1185 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
1186
1187 }
1188 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
1189 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1190 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
1191
1192 }
1193 }
1194}
1195
1196void RewriteModernObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1197 SourceLocation LocStart = (*D.begin())->getLocStart();
1198 if (LocStart.isInvalid())
1199 llvm_unreachable("Invalid SourceLocation");
1200 // FIXME: handle forward protocol that are declared across multiple lines.
1201 ReplaceText(LocStart, 0, "// ");
1202}
1203
1204void
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001205RewriteModernObjC::RewriteForwardProtocolDecl(const SmallVector<Decl *, 8> &DG) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001206 SourceLocation LocStart = DG[0]->getLocStart();
1207 if (LocStart.isInvalid())
1208 llvm_unreachable("Invalid SourceLocation");
1209 // FIXME: handle forward protocol that are declared across multiple lines.
1210 ReplaceText(LocStart, 0, "// ");
1211}
1212
Fariborz Jahanianb3f904f2012-04-03 17:35:38 +00001213void
1214RewriteModernObjC::RewriteLinkageSpec(LinkageSpecDecl *LSD) {
1215 SourceLocation LocStart = LSD->getExternLoc();
1216 if (LocStart.isInvalid())
1217 llvm_unreachable("Invalid extern SourceLocation");
1218
1219 ReplaceText(LocStart, 0, "// ");
1220 if (!LSD->hasBraces())
1221 return;
1222 // FIXME. We don't rewrite well if '{' is not on same line as 'extern'.
1223 SourceLocation LocRBrace = LSD->getRBraceLoc();
1224 if (LocRBrace.isInvalid())
1225 llvm_unreachable("Invalid rbrace SourceLocation");
1226 ReplaceText(LocRBrace, 0, "// ");
1227}
1228
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001229void RewriteModernObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1230 const FunctionType *&FPRetType) {
1231 if (T->isObjCQualifiedIdType())
1232 ResultStr += "id";
1233 else if (T->isFunctionPointerType() ||
1234 T->isBlockPointerType()) {
1235 // needs special handling, since pointer-to-functions have special
1236 // syntax (where a decaration models use).
1237 QualType retType = T;
1238 QualType PointeeTy;
1239 if (const PointerType* PT = retType->getAs<PointerType>())
1240 PointeeTy = PT->getPointeeType();
1241 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
1242 PointeeTy = BPT->getPointeeType();
1243 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
1244 ResultStr += FPRetType->getResultType().getAsString(
1245 Context->getPrintingPolicy());
1246 ResultStr += "(*";
1247 }
1248 } else
1249 ResultStr += T.getAsString(Context->getPrintingPolicy());
1250}
1251
1252void RewriteModernObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1253 ObjCMethodDecl *OMD,
1254 std::string &ResultStr) {
1255 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1256 const FunctionType *FPRetType = 0;
1257 ResultStr += "\nstatic ";
1258 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
1259 ResultStr += " ";
1260
1261 // Unique method name
1262 std::string NameStr;
1263
1264 if (OMD->isInstanceMethod())
1265 NameStr += "_I_";
1266 else
1267 NameStr += "_C_";
1268
1269 NameStr += IDecl->getNameAsString();
1270 NameStr += "_";
1271
1272 if (ObjCCategoryImplDecl *CID =
1273 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
1274 NameStr += CID->getNameAsString();
1275 NameStr += "_";
1276 }
1277 // Append selector names, replacing ':' with '_'
1278 {
1279 std::string selString = OMD->getSelector().getAsString();
1280 int len = selString.size();
1281 for (int i = 0; i < len; i++)
1282 if (selString[i] == ':')
1283 selString[i] = '_';
1284 NameStr += selString;
1285 }
1286 // Remember this name for metadata emission
1287 MethodInternalNames[OMD] = NameStr;
1288 ResultStr += NameStr;
1289
1290 // Rewrite arguments
1291 ResultStr += "(";
1292
1293 // invisible arguments
1294 if (OMD->isInstanceMethod()) {
1295 QualType selfTy = Context->getObjCInterfaceType(IDecl);
1296 selfTy = Context->getPointerType(selfTy);
1297 if (!LangOpts.MicrosoftExt) {
1298 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
1299 ResultStr += "struct ";
1300 }
1301 // When rewriting for Microsoft, explicitly omit the structure name.
1302 ResultStr += IDecl->getNameAsString();
1303 ResultStr += " *";
1304 }
1305 else
1306 ResultStr += Context->getObjCClassType().getAsString(
1307 Context->getPrintingPolicy());
1308
1309 ResultStr += " self, ";
1310 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
1311 ResultStr += " _cmd";
1312
1313 // Method arguments.
1314 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1315 E = OMD->param_end(); PI != E; ++PI) {
1316 ParmVarDecl *PDecl = *PI;
1317 ResultStr += ", ";
1318 if (PDecl->getType()->isObjCQualifiedIdType()) {
1319 ResultStr += "id ";
1320 ResultStr += PDecl->getNameAsString();
1321 } else {
1322 std::string Name = PDecl->getNameAsString();
1323 QualType QT = PDecl->getType();
1324 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian2610f902012-03-27 16:42:20 +00001325 (void)convertBlockPointerToFunctionPointer(QT);
1326 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001327 ResultStr += Name;
1328 }
1329 }
1330 if (OMD->isVariadic())
1331 ResultStr += ", ...";
1332 ResultStr += ") ";
1333
1334 if (FPRetType) {
1335 ResultStr += ")"; // close the precedence "scope" for "*".
1336
1337 // Now, emit the argument types (if any).
1338 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
1339 ResultStr += "(";
1340 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1341 if (i) ResultStr += ", ";
1342 std::string ParamStr = FT->getArgType(i).getAsString(
1343 Context->getPrintingPolicy());
1344 ResultStr += ParamStr;
1345 }
1346 if (FT->isVariadic()) {
1347 if (FT->getNumArgs()) ResultStr += ", ";
1348 ResultStr += "...";
1349 }
1350 ResultStr += ")";
1351 } else {
1352 ResultStr += "()";
1353 }
1354 }
1355}
1356void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) {
1357 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1358 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
1359
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001360 if (IMD) {
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00001361 if (IMD->getIvarRBraceLoc().isValid()) {
1362 ReplaceText(IMD->getLocStart(), 1, "/** ");
1363 ReplaceText(IMD->getIvarRBraceLoc(), 1, "**/ ");
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001364 }
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00001365 else {
1366 InsertText(IMD->getLocStart(), "// ");
1367 }
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001368 }
1369 else
1370 InsertText(CID->getLocStart(), "// ");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001371
1372 for (ObjCCategoryImplDecl::instmeth_iterator
1373 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1374 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
1375 I != E; ++I) {
1376 std::string ResultStr;
1377 ObjCMethodDecl *OMD = *I;
1378 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1379 SourceLocation LocStart = OMD->getLocStart();
1380 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1381
1382 const char *startBuf = SM->getCharacterData(LocStart);
1383 const char *endBuf = SM->getCharacterData(LocEnd);
1384 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1385 }
1386
1387 for (ObjCCategoryImplDecl::classmeth_iterator
1388 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1389 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
1390 I != E; ++I) {
1391 std::string ResultStr;
1392 ObjCMethodDecl *OMD = *I;
1393 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1394 SourceLocation LocStart = OMD->getLocStart();
1395 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1396
1397 const char *startBuf = SM->getCharacterData(LocStart);
1398 const char *endBuf = SM->getCharacterData(LocEnd);
1399 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1400 }
1401 for (ObjCCategoryImplDecl::propimpl_iterator
1402 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
1403 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
1404 I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00001405 RewritePropertyImplDecl(*I, IMD, CID);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001406 }
1407
1408 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
1409}
1410
1411void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00001412 // Do not synthesize more than once.
1413 if (ObjCSynthesizedStructs.count(ClassDecl))
1414 return;
1415 // Make sure super class's are written before current class is written.
1416 ObjCInterfaceDecl *SuperClass = ClassDecl->getSuperClass();
1417 while (SuperClass) {
1418 RewriteInterfaceDecl(SuperClass);
1419 SuperClass = SuperClass->getSuperClass();
1420 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001421 std::string ResultStr;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00001422 if (!ObjCWrittenInterfaces.count(ClassDecl->getCanonicalDecl())) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001423 // we haven't seen a forward decl - generate a typedef.
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001424 RewriteOneForwardClassDecl(ClassDecl, ResultStr);
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00001425 RewriteIvarOffsetSymbols(ClassDecl, ResultStr);
1426
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001427 RewriteObjCInternalStruct(ClassDecl, ResultStr);
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00001428 // Mark this typedef as having been written into its c++ equivalent.
1429 ObjCWrittenInterfaces.insert(ClassDecl->getCanonicalDecl());
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001430
1431 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001432 E = ClassDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001433 RewriteProperty(*I);
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001434 for (ObjCInterfaceDecl::instmeth_iterator
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001435 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001436 I != E; ++I)
1437 RewriteMethodDeclaration(*I);
1438 for (ObjCInterfaceDecl::classmeth_iterator
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001439 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001440 I != E; ++I)
1441 RewriteMethodDeclaration(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001442
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001443 // Lastly, comment out the @end.
1444 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1445 "/* @end */");
1446 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001447}
1448
1449Stmt *RewriteModernObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1450 SourceRange OldRange = PseudoOp->getSourceRange();
1451
1452 // We just magically know some things about the structure of this
1453 // expression.
1454 ObjCMessageExpr *OldMsg =
1455 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1456 PseudoOp->getNumSemanticExprs() - 1));
1457
1458 // Because the rewriter doesn't allow us to rewrite rewritten code,
1459 // we need to suppress rewriting the sub-statements.
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001460 Expr *Base;
1461 SmallVector<Expr*, 2> Args;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001462 {
1463 DisableReplaceStmtScope S(*this);
1464
1465 // Rebuild the base expression if we have one.
1466 Base = 0;
1467 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1468 Base = OldMsg->getInstanceReceiver();
1469 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1470 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1471 }
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001472
1473 unsigned numArgs = OldMsg->getNumArgs();
1474 for (unsigned i = 0; i < numArgs; i++) {
1475 Expr *Arg = OldMsg->getArg(i);
1476 if (isa<OpaqueValueExpr>(Arg))
1477 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1478 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1479 Args.push_back(Arg);
1480 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001481 }
1482
1483 // TODO: avoid this copy.
1484 SmallVector<SourceLocation, 1> SelLocs;
1485 OldMsg->getSelectorLocs(SelLocs);
1486
1487 ObjCMessageExpr *NewMsg = 0;
1488 switch (OldMsg->getReceiverKind()) {
1489 case ObjCMessageExpr::Class:
1490 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1491 OldMsg->getValueKind(),
1492 OldMsg->getLeftLoc(),
1493 OldMsg->getClassReceiverTypeInfo(),
1494 OldMsg->getSelector(),
1495 SelLocs,
1496 OldMsg->getMethodDecl(),
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001497 Args,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001498 OldMsg->getRightLoc(),
1499 OldMsg->isImplicit());
1500 break;
1501
1502 case ObjCMessageExpr::Instance:
1503 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1504 OldMsg->getValueKind(),
1505 OldMsg->getLeftLoc(),
1506 Base,
1507 OldMsg->getSelector(),
1508 SelLocs,
1509 OldMsg->getMethodDecl(),
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001510 Args,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001511 OldMsg->getRightLoc(),
1512 OldMsg->isImplicit());
1513 break;
1514
1515 case ObjCMessageExpr::SuperClass:
1516 case ObjCMessageExpr::SuperInstance:
1517 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1518 OldMsg->getValueKind(),
1519 OldMsg->getLeftLoc(),
1520 OldMsg->getSuperLoc(),
1521 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1522 OldMsg->getSuperType(),
1523 OldMsg->getSelector(),
1524 SelLocs,
1525 OldMsg->getMethodDecl(),
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001526 Args,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001527 OldMsg->getRightLoc(),
1528 OldMsg->isImplicit());
1529 break;
1530 }
1531
1532 Stmt *Replacement = SynthMessageExpr(NewMsg);
1533 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1534 return Replacement;
1535}
1536
1537Stmt *RewriteModernObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1538 SourceRange OldRange = PseudoOp->getSourceRange();
1539
1540 // We just magically know some things about the structure of this
1541 // expression.
1542 ObjCMessageExpr *OldMsg =
1543 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1544
1545 // Because the rewriter doesn't allow us to rewrite rewritten code,
1546 // we need to suppress rewriting the sub-statements.
1547 Expr *Base = 0;
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001548 SmallVector<Expr*, 1> Args;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001549 {
1550 DisableReplaceStmtScope S(*this);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001551 // Rebuild the base expression if we have one.
1552 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1553 Base = OldMsg->getInstanceReceiver();
1554 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1555 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1556 }
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001557 unsigned numArgs = OldMsg->getNumArgs();
1558 for (unsigned i = 0; i < numArgs; i++) {
1559 Expr *Arg = OldMsg->getArg(i);
1560 if (isa<OpaqueValueExpr>(Arg))
1561 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1562 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1563 Args.push_back(Arg);
1564 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001565 }
1566
1567 // Intentionally empty.
1568 SmallVector<SourceLocation, 1> SelLocs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001569
1570 ObjCMessageExpr *NewMsg = 0;
1571 switch (OldMsg->getReceiverKind()) {
1572 case ObjCMessageExpr::Class:
1573 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1574 OldMsg->getValueKind(),
1575 OldMsg->getLeftLoc(),
1576 OldMsg->getClassReceiverTypeInfo(),
1577 OldMsg->getSelector(),
1578 SelLocs,
1579 OldMsg->getMethodDecl(),
1580 Args,
1581 OldMsg->getRightLoc(),
1582 OldMsg->isImplicit());
1583 break;
1584
1585 case ObjCMessageExpr::Instance:
1586 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1587 OldMsg->getValueKind(),
1588 OldMsg->getLeftLoc(),
1589 Base,
1590 OldMsg->getSelector(),
1591 SelLocs,
1592 OldMsg->getMethodDecl(),
1593 Args,
1594 OldMsg->getRightLoc(),
1595 OldMsg->isImplicit());
1596 break;
1597
1598 case ObjCMessageExpr::SuperClass:
1599 case ObjCMessageExpr::SuperInstance:
1600 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1601 OldMsg->getValueKind(),
1602 OldMsg->getLeftLoc(),
1603 OldMsg->getSuperLoc(),
1604 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1605 OldMsg->getSuperType(),
1606 OldMsg->getSelector(),
1607 SelLocs,
1608 OldMsg->getMethodDecl(),
1609 Args,
1610 OldMsg->getRightLoc(),
1611 OldMsg->isImplicit());
1612 break;
1613 }
1614
1615 Stmt *Replacement = SynthMessageExpr(NewMsg);
1616 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1617 return Replacement;
1618}
1619
1620/// SynthCountByEnumWithState - To print:
1621/// ((unsigned int (*)
1622/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1623/// (void *)objc_msgSend)((id)l_collection,
1624/// sel_registerName(
1625/// "countByEnumeratingWithState:objects:count:"),
1626/// &enumState,
1627/// (id *)__rw_items, (unsigned int)16)
1628///
1629void RewriteModernObjC::SynthCountByEnumWithState(std::string &buf) {
1630 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1631 "id *, unsigned int))(void *)objc_msgSend)";
1632 buf += "\n\t\t";
1633 buf += "((id)l_collection,\n\t\t";
1634 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1635 buf += "\n\t\t";
1636 buf += "&enumState, "
1637 "(id *)__rw_items, (unsigned int)16)";
1638}
1639
1640/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1641/// statement to exit to its outer synthesized loop.
1642///
1643Stmt *RewriteModernObjC::RewriteBreakStmt(BreakStmt *S) {
1644 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1645 return S;
1646 // replace break with goto __break_label
1647 std::string buf;
1648
1649 SourceLocation startLoc = S->getLocStart();
1650 buf = "goto __break_label_";
1651 buf += utostr(ObjCBcLabelNo.back());
1652 ReplaceText(startLoc, strlen("break"), buf);
1653
1654 return 0;
1655}
1656
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00001657void RewriteModernObjC::ConvertSourceLocationToLineDirective(
1658 SourceLocation Loc,
1659 std::string &LineString) {
Fariborz Jahanianada71912013-02-08 00:27:34 +00001660 if (Loc.isFileID() && GenerateLineInfo) {
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00001661 LineString += "\n#line ";
1662 PresumedLoc PLoc = SM->getPresumedLoc(Loc);
1663 LineString += utostr(PLoc.getLine());
1664 LineString += " \"";
1665 LineString += Lexer::Stringify(PLoc.getFilename());
1666 LineString += "\"\n";
1667 }
1668}
1669
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001670/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1671/// statement to continue with its inner synthesized loop.
1672///
1673Stmt *RewriteModernObjC::RewriteContinueStmt(ContinueStmt *S) {
1674 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1675 return S;
1676 // replace continue with goto __continue_label
1677 std::string buf;
1678
1679 SourceLocation startLoc = S->getLocStart();
1680 buf = "goto __continue_label_";
1681 buf += utostr(ObjCBcLabelNo.back());
1682 ReplaceText(startLoc, strlen("continue"), buf);
1683
1684 return 0;
1685}
1686
1687/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
1688/// It rewrites:
1689/// for ( type elem in collection) { stmts; }
1690
1691/// Into:
1692/// {
1693/// type elem;
1694/// struct __objcFastEnumerationState enumState = { 0 };
1695/// id __rw_items[16];
1696/// id l_collection = (id)collection;
1697/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1698/// objects:__rw_items count:16];
1699/// if (limit) {
1700/// unsigned long startMutations = *enumState.mutationsPtr;
1701/// do {
1702/// unsigned long counter = 0;
1703/// do {
1704/// if (startMutations != *enumState.mutationsPtr)
1705/// objc_enumerationMutation(l_collection);
1706/// elem = (type)enumState.itemsPtr[counter++];
1707/// stmts;
1708/// __continue_label: ;
1709/// } while (counter < limit);
1710/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1711/// objects:__rw_items count:16]);
1712/// elem = nil;
1713/// __break_label: ;
1714/// }
1715/// else
1716/// elem = nil;
1717/// }
1718///
1719Stmt *RewriteModernObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1720 SourceLocation OrigEnd) {
1721 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1722 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1723 "ObjCForCollectionStmt Statement stack mismatch");
1724 assert(!ObjCBcLabelNo.empty() &&
1725 "ObjCForCollectionStmt - Label No stack empty");
1726
1727 SourceLocation startLoc = S->getLocStart();
1728 const char *startBuf = SM->getCharacterData(startLoc);
1729 StringRef elementName;
1730 std::string elementTypeAsString;
1731 std::string buf;
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00001732 // line directive first.
1733 SourceLocation ForEachLoc = S->getForLoc();
1734 ConvertSourceLocationToLineDirective(ForEachLoc, buf);
1735 buf += "{\n\t";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001736 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1737 // type elem;
1738 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1739 QualType ElementType = cast<ValueDecl>(D)->getType();
1740 if (ElementType->isObjCQualifiedIdType() ||
1741 ElementType->isObjCQualifiedInterfaceType())
1742 // Simply use 'id' for all qualified types.
1743 elementTypeAsString = "id";
1744 else
1745 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
1746 buf += elementTypeAsString;
1747 buf += " ";
1748 elementName = D->getName();
1749 buf += elementName;
1750 buf += ";\n\t";
1751 }
1752 else {
1753 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1754 elementName = DR->getDecl()->getName();
1755 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1756 if (VD->getType()->isObjCQualifiedIdType() ||
1757 VD->getType()->isObjCQualifiedInterfaceType())
1758 // Simply use 'id' for all qualified types.
1759 elementTypeAsString = "id";
1760 else
1761 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
1762 }
1763
1764 // struct __objcFastEnumerationState enumState = { 0 };
1765 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1766 // id __rw_items[16];
1767 buf += "id __rw_items[16];\n\t";
1768 // id l_collection = (id)
1769 buf += "id l_collection = (id)";
1770 // Find start location of 'collection' the hard way!
1771 const char *startCollectionBuf = startBuf;
1772 startCollectionBuf += 3; // skip 'for'
1773 startCollectionBuf = strchr(startCollectionBuf, '(');
1774 startCollectionBuf++; // skip '('
1775 // find 'in' and skip it.
1776 while (*startCollectionBuf != ' ' ||
1777 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1778 (*(startCollectionBuf+3) != ' ' &&
1779 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1780 startCollectionBuf++;
1781 startCollectionBuf += 3;
1782
1783 // Replace: "for (type element in" with string constructed thus far.
1784 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1785 // Replace ')' in for '(' type elem in collection ')' with ';'
1786 SourceLocation rightParenLoc = S->getRParenLoc();
1787 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1788 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
1789 buf = ";\n\t";
1790
1791 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1792 // objects:__rw_items count:16];
1793 // which is synthesized into:
1794 // unsigned int limit =
1795 // ((unsigned int (*)
1796 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1797 // (void *)objc_msgSend)((id)l_collection,
1798 // sel_registerName(
1799 // "countByEnumeratingWithState:objects:count:"),
1800 // (struct __objcFastEnumerationState *)&state,
1801 // (id *)__rw_items, (unsigned int)16);
1802 buf += "unsigned long limit =\n\t\t";
1803 SynthCountByEnumWithState(buf);
1804 buf += ";\n\t";
1805 /// if (limit) {
1806 /// unsigned long startMutations = *enumState.mutationsPtr;
1807 /// do {
1808 /// unsigned long counter = 0;
1809 /// do {
1810 /// if (startMutations != *enumState.mutationsPtr)
1811 /// objc_enumerationMutation(l_collection);
1812 /// elem = (type)enumState.itemsPtr[counter++];
1813 buf += "if (limit) {\n\t";
1814 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1815 buf += "do {\n\t\t";
1816 buf += "unsigned long counter = 0;\n\t\t";
1817 buf += "do {\n\t\t\t";
1818 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1819 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1820 buf += elementName;
1821 buf += " = (";
1822 buf += elementTypeAsString;
1823 buf += ")enumState.itemsPtr[counter++];";
1824 // Replace ')' in for '(' type elem in collection ')' with all of these.
1825 ReplaceText(lparenLoc, 1, buf);
1826
1827 /// __continue_label: ;
1828 /// } while (counter < limit);
1829 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1830 /// objects:__rw_items count:16]);
1831 /// elem = nil;
1832 /// __break_label: ;
1833 /// }
1834 /// else
1835 /// elem = nil;
1836 /// }
1837 ///
1838 buf = ";\n\t";
1839 buf += "__continue_label_";
1840 buf += utostr(ObjCBcLabelNo.back());
1841 buf += ": ;";
1842 buf += "\n\t\t";
1843 buf += "} while (counter < limit);\n\t";
1844 buf += "} while (limit = ";
1845 SynthCountByEnumWithState(buf);
1846 buf += ");\n\t";
1847 buf += elementName;
1848 buf += " = ((";
1849 buf += elementTypeAsString;
1850 buf += ")0);\n\t";
1851 buf += "__break_label_";
1852 buf += utostr(ObjCBcLabelNo.back());
1853 buf += ": ;\n\t";
1854 buf += "}\n\t";
1855 buf += "else\n\t\t";
1856 buf += elementName;
1857 buf += " = ((";
1858 buf += elementTypeAsString;
1859 buf += ")0);\n\t";
1860 buf += "}\n";
1861
1862 // Insert all these *after* the statement body.
1863 // FIXME: If this should support Obj-C++, support CXXTryStmt
1864 if (isa<CompoundStmt>(S->getBody())) {
1865 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
1866 InsertText(endBodyLoc, buf);
1867 } else {
1868 /* Need to treat single statements specially. For example:
1869 *
1870 * for (A *a in b) if (stuff()) break;
1871 * for (A *a in b) xxxyy;
1872 *
1873 * The following code simply scans ahead to the semi to find the actual end.
1874 */
1875 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1876 const char *semiBuf = strchr(stmtBuf, ';');
1877 assert(semiBuf && "Can't find ';'");
1878 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
1879 InsertText(endBodyLoc, buf);
1880 }
1881 Stmts.pop_back();
1882 ObjCBcLabelNo.pop_back();
1883 return 0;
1884}
1885
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001886static void Write_RethrowObject(std::string &buf) {
1887 buf += "{ struct _FIN { _FIN(id reth) : rethrow(reth) {}\n";
1888 buf += "\t~_FIN() { if (rethrow) objc_exception_throw(rethrow); }\n";
1889 buf += "\tid rethrow;\n";
1890 buf += "\t} _fin_force_rethow(_rethrow);";
1891}
1892
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001893/// RewriteObjCSynchronizedStmt -
1894/// This routine rewrites @synchronized(expr) stmt;
1895/// into:
1896/// objc_sync_enter(expr);
1897/// @try stmt @finally { objc_sync_exit(expr); }
1898///
1899Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1900 // Get the start location and compute the semi location.
1901 SourceLocation startLoc = S->getLocStart();
1902 const char *startBuf = SM->getCharacterData(startLoc);
1903
1904 assert((*startBuf == '@') && "bogus @synchronized location");
1905
1906 std::string buf;
Fariborz Jahanian43f4f1e2012-11-07 00:43:05 +00001907 SourceLocation SynchLoc = S->getAtSynchronizedLoc();
1908 ConvertSourceLocationToLineDirective(SynchLoc, buf);
1909 buf += "{ id _rethrow = 0; id _sync_obj = ";
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001910
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001911 const char *lparenBuf = startBuf;
1912 while (*lparenBuf != '(') lparenBuf++;
1913 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001914
1915 buf = "; objc_sync_enter(_sync_obj);\n";
1916 buf += "try {\n\tstruct _SYNC_EXIT { _SYNC_EXIT(id arg) : sync_exit(arg) {}";
1917 buf += "\n\t~_SYNC_EXIT() {objc_sync_exit(sync_exit);}";
1918 buf += "\n\tid sync_exit;";
1919 buf += "\n\t} _sync_exit(_sync_obj);\n";
1920
1921 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1922 // the sync expression is typically a message expression that's already
1923 // been rewritten! (which implies the SourceLocation's are invalid).
1924 SourceLocation RParenExprLoc = S->getSynchBody()->getLocStart();
1925 const char *RParenExprLocBuf = SM->getCharacterData(RParenExprLoc);
1926 while (*RParenExprLocBuf != ')') RParenExprLocBuf--;
1927 RParenExprLoc = startLoc.getLocWithOffset(RParenExprLocBuf-startBuf);
1928
1929 SourceLocation LBranceLoc = S->getSynchBody()->getLocStart();
1930 const char *LBraceLocBuf = SM->getCharacterData(LBranceLoc);
1931 assert (*LBraceLocBuf == '{');
1932 ReplaceText(RParenExprLoc, (LBraceLocBuf - SM->getCharacterData(RParenExprLoc) + 1), buf);
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001933
Fariborz Jahanianb655bf02012-03-16 21:43:45 +00001934 SourceLocation startRBraceLoc = S->getSynchBody()->getLocEnd();
Matt Beaumont-Gay9ab511c2012-03-16 22:20:39 +00001935 assert((*SM->getCharacterData(startRBraceLoc) == '}') &&
1936 "bogus @synchronized block");
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001937
1938 buf = "} catch (id e) {_rethrow = e;}\n";
1939 Write_RethrowObject(buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001940 buf += "}\n";
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001941 buf += "}\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001942
Fariborz Jahanianb655bf02012-03-16 21:43:45 +00001943 ReplaceText(startRBraceLoc, 1, buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001944
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001945 return 0;
1946}
1947
1948void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S)
1949{
1950 // Perform a bottom up traversal of all children.
1951 for (Stmt::child_range CI = S->children(); CI; ++CI)
1952 if (*CI)
1953 WarnAboutReturnGotoStmts(*CI);
1954
1955 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
1956 Diags.Report(Context->getFullLoc(S->getLocStart()),
1957 TryFinallyContainsReturnDiag);
1958 }
1959 return;
1960}
1961
Fariborz Jahanian042b91d2012-05-23 23:47:20 +00001962Stmt *RewriteModernObjC::RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) {
1963 SourceLocation startLoc = S->getAtLoc();
1964 ReplaceText(startLoc, strlen("@autoreleasepool"), "/* @autoreleasepool */");
Fariborz Jahanianc9b72b62012-05-24 22:59:56 +00001965 ReplaceText(S->getSubStmt()->getLocStart(), 1,
1966 "{ __AtAutoreleasePool __autoreleasepool; ");
Fariborz Jahanian042b91d2012-05-23 23:47:20 +00001967
1968 return 0;
1969}
1970
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001971Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001972 ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt();
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001973 bool noCatch = S->getNumCatchStmts() == 0;
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001974 std::string buf;
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00001975 SourceLocation TryLocation = S->getAtTryLoc();
1976 ConvertSourceLocationToLineDirective(TryLocation, buf);
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001977
1978 if (finalStmt) {
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001979 if (noCatch)
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00001980 buf += "{ id volatile _rethrow = 0;\n";
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001981 else {
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00001982 buf += "{ id volatile _rethrow = 0;\ntry {\n";
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001983 }
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001984 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001985 // Get the start location and compute the semi location.
1986 SourceLocation startLoc = S->getLocStart();
1987 const char *startBuf = SM->getCharacterData(startLoc);
1988
1989 assert((*startBuf == '@') && "bogus @try location");
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001990 if (finalStmt)
1991 ReplaceText(startLoc, 1, buf);
1992 else
1993 // @try -> try
1994 ReplaceText(startLoc, 1, "");
1995
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001996 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1997 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Fariborz Jahanian4c148812012-03-15 20:11:10 +00001998 VarDecl *catchDecl = Catch->getCatchParamDecl();
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001999
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002000 startLoc = Catch->getLocStart();
Fariborz Jahanian4c148812012-03-15 20:11:10 +00002001 bool AtRemoved = false;
2002 if (catchDecl) {
2003 QualType t = catchDecl->getType();
2004 if (const ObjCObjectPointerType *Ptr = t->getAs<ObjCObjectPointerType>()) {
2005 // Should be a pointer to a class.
2006 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
2007 if (IDecl) {
2008 std::string Result;
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00002009 ConvertSourceLocationToLineDirective(Catch->getLocStart(), Result);
2010
Fariborz Jahanian4c148812012-03-15 20:11:10 +00002011 startBuf = SM->getCharacterData(startLoc);
2012 assert((*startBuf == '@') && "bogus @catch location");
2013 SourceLocation rParenLoc = Catch->getRParenLoc();
2014 const char *rParenBuf = SM->getCharacterData(rParenLoc);
2015
2016 // _objc_exc_Foo *_e as argument to catch.
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00002017 Result += "catch (_objc_exc_"; Result += IDecl->getNameAsString();
Fariborz Jahanian4c148812012-03-15 20:11:10 +00002018 Result += " *_"; Result += catchDecl->getNameAsString();
2019 Result += ")";
2020 ReplaceText(startLoc, rParenBuf-startBuf+1, Result);
2021 // Foo *e = (Foo *)_e;
2022 Result.clear();
2023 Result = "{ ";
2024 Result += IDecl->getNameAsString();
2025 Result += " *"; Result += catchDecl->getNameAsString();
2026 Result += " = ("; Result += IDecl->getNameAsString(); Result += "*)";
2027 Result += "_"; Result += catchDecl->getNameAsString();
2028
2029 Result += "; ";
2030 SourceLocation lBraceLoc = Catch->getCatchBody()->getLocStart();
2031 ReplaceText(lBraceLoc, 1, Result);
2032 AtRemoved = true;
2033 }
2034 }
2035 }
2036 if (!AtRemoved)
2037 // @catch -> catch
2038 ReplaceText(startLoc, 1, "");
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00002039
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002040 }
Fariborz Jahanian220419a2012-03-15 23:50:33 +00002041 if (finalStmt) {
2042 buf.clear();
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00002043 SourceLocation FinallyLoc = finalStmt->getLocStart();
2044
2045 if (noCatch) {
2046 ConvertSourceLocationToLineDirective(FinallyLoc, buf);
2047 buf += "catch (id e) {_rethrow = e;}\n";
2048 }
2049 else {
2050 buf += "}\n";
2051 ConvertSourceLocationToLineDirective(FinallyLoc, buf);
2052 buf += "catch (id e) {_rethrow = e;}\n";
2053 }
2054
Fariborz Jahanian220419a2012-03-15 23:50:33 +00002055 SourceLocation startFinalLoc = finalStmt->getLocStart();
2056 ReplaceText(startFinalLoc, 8, buf);
2057 Stmt *body = finalStmt->getFinallyBody();
2058 SourceLocation startFinalBodyLoc = body->getLocStart();
2059 buf.clear();
Fariborz Jahanian542125f2012-03-16 21:33:16 +00002060 Write_RethrowObject(buf);
Fariborz Jahanian220419a2012-03-15 23:50:33 +00002061 ReplaceText(startFinalBodyLoc, 1, buf);
2062
2063 SourceLocation endFinalBodyLoc = body->getLocEnd();
2064 ReplaceText(endFinalBodyLoc, 1, "}\n}");
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00002065 // Now check for any return/continue/go statements within the @try.
2066 WarnAboutReturnGotoStmts(S->getTryBody());
Fariborz Jahanian220419a2012-03-15 23:50:33 +00002067 }
2068
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002069 return 0;
2070}
2071
2072// This can't be done with ReplaceStmt(S, ThrowExpr), since
2073// the throw expression is typically a message expression that's already
2074// been rewritten! (which implies the SourceLocation's are invalid).
2075Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
2076 // Get the start location and compute the semi location.
2077 SourceLocation startLoc = S->getLocStart();
2078 const char *startBuf = SM->getCharacterData(startLoc);
2079
2080 assert((*startBuf == '@') && "bogus @throw location");
2081
2082 std::string buf;
2083 /* void objc_exception_throw(id) __attribute__((noreturn)); */
2084 if (S->getThrowExpr())
2085 buf = "objc_exception_throw(";
Fariborz Jahanian40539462012-03-16 16:52:06 +00002086 else
2087 buf = "throw";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002088
2089 // handle "@ throw" correctly.
2090 const char *wBuf = strchr(startBuf, 'w');
2091 assert((*wBuf == 'w') && "@throw: can't find 'w'");
2092 ReplaceText(startLoc, wBuf-startBuf+1, buf);
2093
Fariborz Jahaniana09cd812013-02-11 19:30:33 +00002094 SourceLocation endLoc = S->getLocEnd();
2095 const char *endBuf = SM->getCharacterData(endLoc);
2096 const char *semiBuf = strchr(endBuf, ';');
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002097 assert((*semiBuf == ';') && "@throw: can't find ';'");
2098 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Fariborz Jahanian40539462012-03-16 16:52:06 +00002099 if (S->getThrowExpr())
2100 ReplaceText(semiLoc, 1, ");");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002101 return 0;
2102}
2103
2104Stmt *RewriteModernObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
2105 // Create a new string expression.
2106 QualType StrType = Context->getPointerType(Context->CharTy);
2107 std::string StrEncoding;
2108 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
2109 Expr *Replacement = StringLiteral::Create(*Context, StrEncoding,
2110 StringLiteral::Ascii, false,
2111 StrType, SourceLocation());
2112 ReplaceStmt(Exp, Replacement);
2113
2114 // Replace this subexpr in the parent.
2115 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2116 return Replacement;
2117}
2118
2119Stmt *RewriteModernObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
2120 if (!SelGetUidFunctionDecl)
2121 SynthSelGetUidFunctionDecl();
2122 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2123 // Create a call to sel_registerName("selName").
2124 SmallVector<Expr*, 8> SelExprs;
2125 QualType argType = Context->getPointerType(Context->CharTy);
2126 SelExprs.push_back(StringLiteral::Create(*Context,
2127 Exp->getSelector().getAsString(),
2128 StringLiteral::Ascii, false,
2129 argType, SourceLocation()));
2130 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2131 &SelExprs[0], SelExprs.size());
2132 ReplaceStmt(Exp, SelExp);
2133 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2134 return SelExp;
2135}
2136
2137CallExpr *RewriteModernObjC::SynthesizeCallToFunctionDecl(
2138 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2139 SourceLocation EndLoc) {
2140 // Get the type, we will need to reference it in a couple spots.
2141 QualType msgSendType = FD->getType();
2142
2143 // Create a reference to the objc_msgSend() declaration.
2144 DeclRefExpr *DRE =
John McCallf4b88a42012-03-10 09:33:50 +00002145 new (Context) DeclRefExpr(FD, false, msgSendType, VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002146
2147 // Now, we cast the reference to a pointer to the objc_msgSend type.
2148 QualType pToFunc = Context->getPointerType(msgSendType);
2149 ImplicitCastExpr *ICE =
2150 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
2151 DRE, 0, VK_RValue);
2152
2153 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2154
2155 CallExpr *Exp =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002156 new (Context) CallExpr(*Context, ICE, llvm::makeArrayRef(args, nargs),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002157 FT->getCallResultType(*Context),
2158 VK_RValue, EndLoc);
2159 return Exp;
2160}
2161
2162static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2163 const char *&startRef, const char *&endRef) {
2164 while (startBuf < endBuf) {
2165 if (*startBuf == '<')
2166 startRef = startBuf; // mark the start.
2167 if (*startBuf == '>') {
2168 if (startRef && *startRef == '<') {
2169 endRef = startBuf; // mark the end.
2170 return true;
2171 }
2172 return false;
2173 }
2174 startBuf++;
2175 }
2176 return false;
2177}
2178
2179static void scanToNextArgument(const char *&argRef) {
2180 int angle = 0;
2181 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2182 if (*argRef == '<')
2183 angle++;
2184 else if (*argRef == '>')
2185 angle--;
2186 argRef++;
2187 }
2188 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2189}
2190
2191bool RewriteModernObjC::needToScanForQualifiers(QualType T) {
2192 if (T->isObjCQualifiedIdType())
2193 return true;
2194 if (const PointerType *PT = T->getAs<PointerType>()) {
2195 if (PT->getPointeeType()->isObjCQualifiedIdType())
2196 return true;
2197 }
2198 if (T->isObjCObjectPointerType()) {
2199 T = T->getPointeeType();
2200 return T->isObjCQualifiedInterfaceType();
2201 }
2202 if (T->isArrayType()) {
2203 QualType ElemTy = Context->getBaseElementType(T);
2204 return needToScanForQualifiers(ElemTy);
2205 }
2206 return false;
2207}
2208
2209void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2210 QualType Type = E->getType();
2211 if (needToScanForQualifiers(Type)) {
2212 SourceLocation Loc, EndLoc;
2213
2214 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2215 Loc = ECE->getLParenLoc();
2216 EndLoc = ECE->getRParenLoc();
2217 } else {
2218 Loc = E->getLocStart();
2219 EndLoc = E->getLocEnd();
2220 }
2221 // This will defend against trying to rewrite synthesized expressions.
2222 if (Loc.isInvalid() || EndLoc.isInvalid())
2223 return;
2224
2225 const char *startBuf = SM->getCharacterData(Loc);
2226 const char *endBuf = SM->getCharacterData(EndLoc);
2227 const char *startRef = 0, *endRef = 0;
2228 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2229 // Get the locations of the startRef, endRef.
2230 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2231 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2232 // Comment out the protocol references.
2233 InsertText(LessLoc, "/*");
2234 InsertText(GreaterLoc, "*/");
2235 }
2236 }
2237}
2238
2239void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2240 SourceLocation Loc;
2241 QualType Type;
2242 const FunctionProtoType *proto = 0;
2243 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2244 Loc = VD->getLocation();
2245 Type = VD->getType();
2246 }
2247 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2248 Loc = FD->getLocation();
2249 // Check for ObjC 'id' and class types that have been adorned with protocol
2250 // information (id<p>, C<p>*). The protocol references need to be rewritten!
2251 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2252 assert(funcType && "missing function type");
2253 proto = dyn_cast<FunctionProtoType>(funcType);
2254 if (!proto)
2255 return;
2256 Type = proto->getResultType();
2257 }
2258 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2259 Loc = FD->getLocation();
2260 Type = FD->getType();
2261 }
2262 else
2263 return;
2264
2265 if (needToScanForQualifiers(Type)) {
2266 // Since types are unique, we need to scan the buffer.
2267
2268 const char *endBuf = SM->getCharacterData(Loc);
2269 const char *startBuf = endBuf;
2270 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
2271 startBuf--; // scan backward (from the decl location) for return type.
2272 const char *startRef = 0, *endRef = 0;
2273 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2274 // Get the locations of the startRef, endRef.
2275 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2276 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2277 // Comment out the protocol references.
2278 InsertText(LessLoc, "/*");
2279 InsertText(GreaterLoc, "*/");
2280 }
2281 }
2282 if (!proto)
2283 return; // most likely, was a variable
2284 // Now check arguments.
2285 const char *startBuf = SM->getCharacterData(Loc);
2286 const char *startFuncBuf = startBuf;
2287 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2288 if (needToScanForQualifiers(proto->getArgType(i))) {
2289 // Since types are unique, we need to scan the buffer.
2290
2291 const char *endBuf = startBuf;
2292 // scan forward (from the decl location) for argument types.
2293 scanToNextArgument(endBuf);
2294 const char *startRef = 0, *endRef = 0;
2295 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2296 // Get the locations of the startRef, endRef.
2297 SourceLocation LessLoc =
2298 Loc.getLocWithOffset(startRef-startFuncBuf);
2299 SourceLocation GreaterLoc =
2300 Loc.getLocWithOffset(endRef-startFuncBuf+1);
2301 // Comment out the protocol references.
2302 InsertText(LessLoc, "/*");
2303 InsertText(GreaterLoc, "*/");
2304 }
2305 startBuf = ++endBuf;
2306 }
2307 else {
2308 // If the function name is derived from a macro expansion, then the
2309 // argument buffer will not follow the name. Need to speak with Chris.
2310 while (*startBuf && *startBuf != ')' && *startBuf != ',')
2311 startBuf++; // scan forward (from the decl location) for argument types.
2312 startBuf++;
2313 }
2314 }
2315}
2316
2317void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) {
2318 QualType QT = ND->getType();
2319 const Type* TypePtr = QT->getAs<Type>();
2320 if (!isa<TypeOfExprType>(TypePtr))
2321 return;
2322 while (isa<TypeOfExprType>(TypePtr)) {
2323 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2324 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2325 TypePtr = QT->getAs<Type>();
2326 }
2327 // FIXME. This will not work for multiple declarators; as in:
2328 // __typeof__(a) b,c,d;
2329 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2330 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2331 const char *startBuf = SM->getCharacterData(DeclLoc);
2332 if (ND->getInit()) {
2333 std::string Name(ND->getNameAsString());
2334 TypeAsString += " " + Name + " = ";
2335 Expr *E = ND->getInit();
2336 SourceLocation startLoc;
2337 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2338 startLoc = ECE->getLParenLoc();
2339 else
2340 startLoc = E->getLocStart();
2341 startLoc = SM->getExpansionLoc(startLoc);
2342 const char *endBuf = SM->getCharacterData(startLoc);
2343 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2344 }
2345 else {
2346 SourceLocation X = ND->getLocEnd();
2347 X = SM->getExpansionLoc(X);
2348 const char *endBuf = SM->getCharacterData(X);
2349 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2350 }
2351}
2352
2353// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2354void RewriteModernObjC::SynthSelGetUidFunctionDecl() {
2355 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2356 SmallVector<QualType, 16> ArgTys;
2357 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2358 QualType getFuncType =
Jordan Rosebea522f2013-03-08 21:51:21 +00002359 getSimpleFunctionType(Context->getObjCSelType(), ArgTys);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002360 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002361 SourceLocation(),
2362 SourceLocation(),
2363 SelGetUidIdent, getFuncType, 0,
Rafael Espindola8f187f62013-04-03 15:50:00 +00002364 SC_Extern);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002365}
2366
2367void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2368 // declared in <objc/objc.h>
2369 if (FD->getIdentifier() &&
2370 FD->getName() == "sel_registerName") {
2371 SelGetUidFunctionDecl = FD;
2372 return;
2373 }
2374 RewriteObjCQualifiedInterfaceTypes(FD);
2375}
2376
2377void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2378 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2379 const char *argPtr = TypeString.c_str();
2380 if (!strchr(argPtr, '^')) {
2381 Str += TypeString;
2382 return;
2383 }
2384 while (*argPtr) {
2385 Str += (*argPtr == '^' ? '*' : *argPtr);
2386 argPtr++;
2387 }
2388}
2389
2390// FIXME. Consolidate this routine with RewriteBlockPointerType.
2391void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2392 ValueDecl *VD) {
2393 QualType Type = VD->getType();
2394 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2395 const char *argPtr = TypeString.c_str();
2396 int paren = 0;
2397 while (*argPtr) {
2398 switch (*argPtr) {
2399 case '(':
2400 Str += *argPtr;
2401 paren++;
2402 break;
2403 case ')':
2404 Str += *argPtr;
2405 paren--;
2406 break;
2407 case '^':
2408 Str += '*';
2409 if (paren == 1)
2410 Str += VD->getNameAsString();
2411 break;
2412 default:
2413 Str += *argPtr;
2414 break;
2415 }
2416 argPtr++;
2417 }
2418}
2419
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00002420void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2421 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2422 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2423 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2424 if (!proto)
2425 return;
2426 QualType Type = proto->getResultType();
2427 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2428 FdStr += " ";
2429 FdStr += FD->getName();
2430 FdStr += "(";
2431 unsigned numArgs = proto->getNumArgs();
2432 for (unsigned i = 0; i < numArgs; i++) {
2433 QualType ArgType = proto->getArgType(i);
2434 RewriteBlockPointerType(FdStr, ArgType);
2435 if (i+1 < numArgs)
2436 FdStr += ", ";
2437 }
Fariborz Jahanianb5863da2012-04-19 16:30:28 +00002438 if (FD->isVariadic()) {
2439 FdStr += (numArgs > 0) ? ", ...);\n" : "...);\n";
2440 }
2441 else
2442 FdStr += ");\n";
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00002443 InsertText(FunLocStart, FdStr);
2444}
2445
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002446// SynthSuperContructorFunctionDecl - id __rw_objc_super(id obj, id super);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002447void RewriteModernObjC::SynthSuperContructorFunctionDecl() {
2448 if (SuperContructorFunctionDecl)
2449 return;
2450 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2451 SmallVector<QualType, 16> ArgTys;
2452 QualType argT = Context->getObjCIdType();
2453 assert(!argT.isNull() && "Can't find 'id' type");
2454 ArgTys.push_back(argT);
2455 ArgTys.push_back(argT);
2456 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rosebea522f2013-03-08 21:51:21 +00002457 ArgTys);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002458 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002459 SourceLocation(),
2460 SourceLocation(),
2461 msgSendIdent, msgSendType,
Rafael Espindola8f187f62013-04-03 15:50:00 +00002462 0, SC_Extern);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002463}
2464
2465// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2466void RewriteModernObjC::SynthMsgSendFunctionDecl() {
2467 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2468 SmallVector<QualType, 16> ArgTys;
2469 QualType argT = Context->getObjCIdType();
2470 assert(!argT.isNull() && "Can't find 'id' type");
2471 ArgTys.push_back(argT);
2472 argT = Context->getObjCSelType();
2473 assert(!argT.isNull() && "Can't find 'SEL' type");
2474 ArgTys.push_back(argT);
2475 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rosebea522f2013-03-08 21:51:21 +00002476 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002477 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002478 SourceLocation(),
2479 SourceLocation(),
2480 msgSendIdent, msgSendType, 0,
Rafael Espindola8f187f62013-04-03 15:50:00 +00002481 SC_Extern);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002482}
2483
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002484// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(void);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002485void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() {
2486 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002487 SmallVector<QualType, 2> ArgTys;
2488 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002489 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rosebea522f2013-03-08 21:51:21 +00002490 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002491 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002492 SourceLocation(),
2493 SourceLocation(),
2494 msgSendIdent, msgSendType, 0,
Rafael Espindola8f187f62013-04-03 15:50:00 +00002495 SC_Extern);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002496}
2497
2498// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2499void RewriteModernObjC::SynthMsgSendStretFunctionDecl() {
2500 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2501 SmallVector<QualType, 16> ArgTys;
2502 QualType argT = Context->getObjCIdType();
2503 assert(!argT.isNull() && "Can't find 'id' type");
2504 ArgTys.push_back(argT);
2505 argT = Context->getObjCSelType();
2506 assert(!argT.isNull() && "Can't find 'SEL' type");
2507 ArgTys.push_back(argT);
2508 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rosebea522f2013-03-08 21:51:21 +00002509 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002510 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002511 SourceLocation(),
2512 SourceLocation(),
2513 msgSendIdent, msgSendType, 0,
Rafael Espindola8f187f62013-04-03 15:50:00 +00002514 SC_Extern);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002515}
2516
2517// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002518// id objc_msgSendSuper_stret(void);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002519void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() {
2520 IdentifierInfo *msgSendIdent =
2521 &Context->Idents.get("objc_msgSendSuper_stret");
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002522 SmallVector<QualType, 2> ArgTys;
2523 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002524 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rosebea522f2013-03-08 21:51:21 +00002525 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002526 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2527 SourceLocation(),
2528 SourceLocation(),
Chad Rosiere3b29882013-01-04 22:40:33 +00002529 msgSendIdent,
2530 msgSendType, 0,
Rafael Espindola8f187f62013-04-03 15:50:00 +00002531 SC_Extern);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002532}
2533
2534// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2535void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() {
2536 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2537 SmallVector<QualType, 16> ArgTys;
2538 QualType argT = Context->getObjCIdType();
2539 assert(!argT.isNull() && "Can't find 'id' type");
2540 ArgTys.push_back(argT);
2541 argT = Context->getObjCSelType();
2542 assert(!argT.isNull() && "Can't find 'SEL' type");
2543 ArgTys.push_back(argT);
2544 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
Jordan Rosebea522f2013-03-08 21:51:21 +00002545 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002546 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002547 SourceLocation(),
2548 SourceLocation(),
2549 msgSendIdent, msgSendType, 0,
Rafael Espindola8f187f62013-04-03 15:50:00 +00002550 SC_Extern);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002551}
2552
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00002553// SynthGetClassFunctionDecl - Class objc_getClass(const char *name);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002554void RewriteModernObjC::SynthGetClassFunctionDecl() {
2555 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2556 SmallVector<QualType, 16> ArgTys;
2557 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00002558 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Jordan Rosebea522f2013-03-08 21:51:21 +00002559 ArgTys);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002560 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002561 SourceLocation(),
2562 SourceLocation(),
2563 getClassIdent, getClassType, 0,
Rafael Espindola8f187f62013-04-03 15:50:00 +00002564 SC_Extern);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002565}
2566
2567// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2568void RewriteModernObjC::SynthGetSuperClassFunctionDecl() {
2569 IdentifierInfo *getSuperClassIdent =
2570 &Context->Idents.get("class_getSuperclass");
2571 SmallVector<QualType, 16> ArgTys;
2572 ArgTys.push_back(Context->getObjCClassType());
2573 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Jordan Rosebea522f2013-03-08 21:51:21 +00002574 ArgTys);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002575 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2576 SourceLocation(),
2577 SourceLocation(),
2578 getSuperClassIdent,
2579 getClassType, 0,
Rafael Espindola8f187f62013-04-03 15:50:00 +00002580 SC_Extern);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002581}
2582
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00002583// SynthGetMetaClassFunctionDecl - Class objc_getMetaClass(const char *name);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002584void RewriteModernObjC::SynthGetMetaClassFunctionDecl() {
2585 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2586 SmallVector<QualType, 16> ArgTys;
2587 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00002588 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Jordan Rosebea522f2013-03-08 21:51:21 +00002589 ArgTys);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002590 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002591 SourceLocation(),
2592 SourceLocation(),
2593 getClassIdent, getClassType,
Rafael Espindola8f187f62013-04-03 15:50:00 +00002594 0, SC_Extern);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002595}
2596
2597Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
2598 QualType strType = getConstantStringStructType();
2599
2600 std::string S = "__NSConstantStringImpl_";
2601
2602 std::string tmpName = InFileName;
2603 unsigned i;
2604 for (i=0; i < tmpName.length(); i++) {
2605 char c = tmpName.at(i);
2606 // replace any non alphanumeric characters with '_'.
Jordan Rose3f6f51e2013-02-08 22:30:41 +00002607 if (!isAlphanumeric(c))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002608 tmpName[i] = '_';
2609 }
2610 S += tmpName;
2611 S += "_";
2612 S += utostr(NumObjCStringLiterals++);
2613
2614 Preamble += "static __NSConstantStringImpl " + S;
2615 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2616 Preamble += "0x000007c8,"; // utf8_str
2617 // The pretty printer for StringLiteral handles escape characters properly.
2618 std::string prettyBufS;
2619 llvm::raw_string_ostream prettyBuf(prettyBufS);
Richard Smithd1420c62012-08-16 03:56:14 +00002620 Exp->getString()->printPretty(prettyBuf, 0, PrintingPolicy(LangOpts));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002621 Preamble += prettyBuf.str();
2622 Preamble += ",";
2623 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2624
2625 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2626 SourceLocation(), &Context->Idents.get(S),
Rafael Espindola8f187f62013-04-03 15:50:00 +00002627 strType, 0, SC_Static);
John McCallf4b88a42012-03-10 09:33:50 +00002628 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002629 SourceLocation());
2630 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
2631 Context->getPointerType(DRE->getType()),
2632 VK_RValue, OK_Ordinary,
2633 SourceLocation());
2634 // cast to NSConstantString *
2635 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2636 CK_CPointerToObjCPointerCast, Unop);
2637 ReplaceStmt(Exp, cast);
2638 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2639 return cast;
2640}
2641
Fariborz Jahanian55947042012-03-27 20:17:30 +00002642Stmt *RewriteModernObjC::RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp) {
2643 unsigned IntSize =
2644 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
2645
2646 Expr *FlagExp = IntegerLiteral::Create(*Context,
2647 llvm::APInt(IntSize, Exp->getValue()),
2648 Context->IntTy, Exp->getLocation());
2649 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Context->ObjCBuiltinBoolTy,
2650 CK_BitCast, FlagExp);
2651 ParenExpr *PE = new (Context) ParenExpr(Exp->getLocation(), Exp->getExprLoc(),
2652 cast);
2653 ReplaceStmt(Exp, PE);
2654 return PE;
2655}
2656
Patrick Beardeb382ec2012-04-19 00:25:12 +00002657Stmt *RewriteModernObjC::RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp) {
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002658 // synthesize declaration of helper functions needed in this routine.
2659 if (!SelGetUidFunctionDecl)
2660 SynthSelGetUidFunctionDecl();
2661 // use objc_msgSend() for all.
2662 if (!MsgSendFunctionDecl)
2663 SynthMsgSendFunctionDecl();
2664 if (!GetClassFunctionDecl)
2665 SynthGetClassFunctionDecl();
2666
2667 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2668 SourceLocation StartLoc = Exp->getLocStart();
2669 SourceLocation EndLoc = Exp->getLocEnd();
2670
2671 // Synthesize a call to objc_msgSend().
2672 SmallVector<Expr*, 4> MsgExprs;
2673 SmallVector<Expr*, 4> ClsExprs;
2674 QualType argType = Context->getPointerType(Context->CharTy);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002675
Patrick Beardeb382ec2012-04-19 00:25:12 +00002676 // Create a call to objc_getClass("<BoxingClass>"). It will be the 1st argument.
2677 ObjCMethodDecl *BoxingMethod = Exp->getBoxingMethod();
2678 ObjCInterfaceDecl *BoxingClass = BoxingMethod->getClassInterface();
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002679
Patrick Beardeb382ec2012-04-19 00:25:12 +00002680 IdentifierInfo *clsName = BoxingClass->getIdentifier();
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002681 ClsExprs.push_back(StringLiteral::Create(*Context,
2682 clsName->getName(),
2683 StringLiteral::Ascii, false,
2684 argType, SourceLocation()));
2685 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2686 &ClsExprs[0],
2687 ClsExprs.size(),
2688 StartLoc, EndLoc);
2689 MsgExprs.push_back(Cls);
2690
Patrick Beardeb382ec2012-04-19 00:25:12 +00002691 // Create a call to sel_registerName("<BoxingMethod>:"), etc.
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002692 // it will be the 2nd argument.
2693 SmallVector<Expr*, 4> SelExprs;
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002694 SelExprs.push_back(StringLiteral::Create(*Context,
Patrick Beardeb382ec2012-04-19 00:25:12 +00002695 BoxingMethod->getSelector().getAsString(),
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002696 StringLiteral::Ascii, false,
2697 argType, SourceLocation()));
2698 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2699 &SelExprs[0], SelExprs.size(),
2700 StartLoc, EndLoc);
2701 MsgExprs.push_back(SelExp);
2702
Patrick Beardeb382ec2012-04-19 00:25:12 +00002703 // User provided sub-expression is the 3rd, and last, argument.
2704 Expr *subExpr = Exp->getSubExpr();
2705 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(subExpr)) {
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002706 QualType type = ICE->getType();
2707 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2708 CastKind CK = CK_BitCast;
2709 if (SubExpr->getType()->isIntegralType(*Context) && type->isBooleanType())
2710 CK = CK_IntegralToBoolean;
Patrick Beardeb382ec2012-04-19 00:25:12 +00002711 subExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, subExpr);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002712 }
Patrick Beardeb382ec2012-04-19 00:25:12 +00002713 MsgExprs.push_back(subExpr);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002714
2715 SmallVector<QualType, 4> ArgTypes;
2716 ArgTypes.push_back(Context->getObjCIdType());
2717 ArgTypes.push_back(Context->getObjCSelType());
Patrick Beardeb382ec2012-04-19 00:25:12 +00002718 for (ObjCMethodDecl::param_iterator PI = BoxingMethod->param_begin(),
2719 E = BoxingMethod->param_end(); PI != E; ++PI)
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002720 ArgTypes.push_back((*PI)->getType());
Patrick Beardeb382ec2012-04-19 00:25:12 +00002721
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002722 QualType returnType = Exp->getType();
2723 // Get the type, we will need to reference it in a couple spots.
2724 QualType msgSendType = MsgSendFlavor->getType();
2725
2726 // Create a reference to the objc_msgSend() declaration.
2727 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2728 VK_LValue, SourceLocation());
2729
2730 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
Patrick Beardeb382ec2012-04-19 00:25:12 +00002731 Context->getPointerType(Context->VoidTy),
2732 CK_BitCast, DRE);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002733
2734 // Now do the "normal" pointer to function cast.
2735 QualType castType =
Jordan Rosebea522f2013-03-08 21:51:21 +00002736 getSimpleFunctionType(returnType, ArgTypes, BoxingMethod->isVariadic());
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002737 castType = Context->getPointerType(castType);
2738 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2739 cast);
2740
2741 // Don't forget the parens to enforce the proper binding.
2742 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2743
2744 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002745 CallExpr *CE = new (Context) CallExpr(*Context, PE, MsgExprs,
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002746 FT->getResultType(), VK_RValue,
2747 EndLoc);
2748 ReplaceStmt(Exp, CE);
2749 return CE;
2750}
2751
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002752Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) {
2753 // synthesize declaration of helper functions needed in this routine.
2754 if (!SelGetUidFunctionDecl)
2755 SynthSelGetUidFunctionDecl();
2756 // use objc_msgSend() for all.
2757 if (!MsgSendFunctionDecl)
2758 SynthMsgSendFunctionDecl();
2759 if (!GetClassFunctionDecl)
2760 SynthGetClassFunctionDecl();
2761
2762 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2763 SourceLocation StartLoc = Exp->getLocStart();
2764 SourceLocation EndLoc = Exp->getLocEnd();
2765
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002766 // Build the expression: __NSContainer_literal(int, ...).arr
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002767 QualType IntQT = Context->IntTy;
2768 QualType NSArrayFType =
Jordan Rosebea522f2013-03-08 21:51:21 +00002769 getSimpleFunctionType(Context->VoidTy, IntQT, true);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002770 std::string NSArrayFName("__NSContainer_literal");
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002771 FunctionDecl *NSArrayFD = SynthBlockInitFunctionDecl(NSArrayFName);
2772 DeclRefExpr *NSArrayDRE =
2773 new (Context) DeclRefExpr(NSArrayFD, false, NSArrayFType, VK_RValue,
2774 SourceLocation());
2775
2776 SmallVector<Expr*, 16> InitExprs;
2777 unsigned NumElements = Exp->getNumElements();
2778 unsigned UnsignedIntSize =
2779 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2780 Expr *count = IntegerLiteral::Create(*Context,
2781 llvm::APInt(UnsignedIntSize, NumElements),
2782 Context->UnsignedIntTy, SourceLocation());
2783 InitExprs.push_back(count);
2784 for (unsigned i = 0; i < NumElements; i++)
2785 InitExprs.push_back(Exp->getElement(i));
2786 Expr *NSArrayCallExpr =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002787 new (Context) CallExpr(*Context, NSArrayDRE, InitExprs,
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002788 NSArrayFType, VK_LValue, SourceLocation());
2789
2790 FieldDecl *ARRFD = FieldDecl::Create(*Context, 0, SourceLocation(),
2791 SourceLocation(),
2792 &Context->Idents.get("arr"),
2793 Context->getPointerType(Context->VoidPtrTy), 0,
2794 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00002795 ICIS_NoInit);
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002796 MemberExpr *ArrayLiteralME =
2797 new (Context) MemberExpr(NSArrayCallExpr, false, ARRFD,
2798 SourceLocation(),
2799 ARRFD->getType(), VK_LValue,
2800 OK_Ordinary);
2801 QualType ConstIdT = Context->getObjCIdType().withConst();
2802 CStyleCastExpr * ArrayLiteralObjects =
2803 NoTypeInfoCStyleCastExpr(Context,
2804 Context->getPointerType(ConstIdT),
2805 CK_BitCast,
2806 ArrayLiteralME);
2807
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002808 // Synthesize a call to objc_msgSend().
2809 SmallVector<Expr*, 32> MsgExprs;
2810 SmallVector<Expr*, 4> ClsExprs;
2811 QualType argType = Context->getPointerType(Context->CharTy);
2812 QualType expType = Exp->getType();
2813
2814 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2815 ObjCInterfaceDecl *Class =
2816 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2817
2818 IdentifierInfo *clsName = Class->getIdentifier();
2819 ClsExprs.push_back(StringLiteral::Create(*Context,
2820 clsName->getName(),
2821 StringLiteral::Ascii, false,
2822 argType, SourceLocation()));
2823 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2824 &ClsExprs[0],
2825 ClsExprs.size(),
2826 StartLoc, EndLoc);
2827 MsgExprs.push_back(Cls);
2828
2829 // Create a call to sel_registerName("arrayWithObjects:count:").
2830 // it will be the 2nd argument.
2831 SmallVector<Expr*, 4> SelExprs;
2832 ObjCMethodDecl *ArrayMethod = Exp->getArrayWithObjectsMethod();
2833 SelExprs.push_back(StringLiteral::Create(*Context,
2834 ArrayMethod->getSelector().getAsString(),
2835 StringLiteral::Ascii, false,
2836 argType, SourceLocation()));
2837 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2838 &SelExprs[0], SelExprs.size(),
2839 StartLoc, EndLoc);
2840 MsgExprs.push_back(SelExp);
2841
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002842 // (const id [])objects
2843 MsgExprs.push_back(ArrayLiteralObjects);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002844
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002845 // (NSUInteger)cnt
2846 Expr *cnt = IntegerLiteral::Create(*Context,
2847 llvm::APInt(UnsignedIntSize, NumElements),
2848 Context->UnsignedIntTy, SourceLocation());
2849 MsgExprs.push_back(cnt);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002850
2851
2852 SmallVector<QualType, 4> ArgTypes;
2853 ArgTypes.push_back(Context->getObjCIdType());
2854 ArgTypes.push_back(Context->getObjCSelType());
2855 for (ObjCMethodDecl::param_iterator PI = ArrayMethod->param_begin(),
2856 E = ArrayMethod->param_end(); PI != E; ++PI)
2857 ArgTypes.push_back((*PI)->getType());
2858
2859 QualType returnType = Exp->getType();
2860 // Get the type, we will need to reference it in a couple spots.
2861 QualType msgSendType = MsgSendFlavor->getType();
2862
2863 // Create a reference to the objc_msgSend() declaration.
2864 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2865 VK_LValue, SourceLocation());
2866
2867 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2868 Context->getPointerType(Context->VoidTy),
2869 CK_BitCast, DRE);
2870
2871 // Now do the "normal" pointer to function cast.
2872 QualType castType =
Jordan Rosebea522f2013-03-08 21:51:21 +00002873 getSimpleFunctionType(returnType, ArgTypes, ArrayMethod->isVariadic());
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002874 castType = Context->getPointerType(castType);
2875 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2876 cast);
2877
2878 // Don't forget the parens to enforce the proper binding.
2879 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2880
2881 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002882 CallExpr *CE = new (Context) CallExpr(*Context, PE, MsgExprs,
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002883 FT->getResultType(), VK_RValue,
2884 EndLoc);
2885 ReplaceStmt(Exp, CE);
2886 return CE;
2887}
2888
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002889Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp) {
2890 // synthesize declaration of helper functions needed in this routine.
2891 if (!SelGetUidFunctionDecl)
2892 SynthSelGetUidFunctionDecl();
2893 // use objc_msgSend() for all.
2894 if (!MsgSendFunctionDecl)
2895 SynthMsgSendFunctionDecl();
2896 if (!GetClassFunctionDecl)
2897 SynthGetClassFunctionDecl();
2898
2899 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2900 SourceLocation StartLoc = Exp->getLocStart();
2901 SourceLocation EndLoc = Exp->getLocEnd();
2902
2903 // Build the expression: __NSContainer_literal(int, ...).arr
2904 QualType IntQT = Context->IntTy;
2905 QualType NSDictFType =
Jordan Rosebea522f2013-03-08 21:51:21 +00002906 getSimpleFunctionType(Context->VoidTy, IntQT, true);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002907 std::string NSDictFName("__NSContainer_literal");
2908 FunctionDecl *NSDictFD = SynthBlockInitFunctionDecl(NSDictFName);
2909 DeclRefExpr *NSDictDRE =
2910 new (Context) DeclRefExpr(NSDictFD, false, NSDictFType, VK_RValue,
2911 SourceLocation());
2912
2913 SmallVector<Expr*, 16> KeyExprs;
2914 SmallVector<Expr*, 16> ValueExprs;
2915
2916 unsigned NumElements = Exp->getNumElements();
2917 unsigned UnsignedIntSize =
2918 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2919 Expr *count = IntegerLiteral::Create(*Context,
2920 llvm::APInt(UnsignedIntSize, NumElements),
2921 Context->UnsignedIntTy, SourceLocation());
2922 KeyExprs.push_back(count);
2923 ValueExprs.push_back(count);
2924 for (unsigned i = 0; i < NumElements; i++) {
2925 ObjCDictionaryElement Element = Exp->getKeyValueElement(i);
2926 KeyExprs.push_back(Element.Key);
2927 ValueExprs.push_back(Element.Value);
2928 }
2929
2930 // (const id [])objects
2931 Expr *NSValueCallExpr =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002932 new (Context) CallExpr(*Context, NSDictDRE, ValueExprs,
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002933 NSDictFType, VK_LValue, SourceLocation());
2934
2935 FieldDecl *ARRFD = FieldDecl::Create(*Context, 0, SourceLocation(),
2936 SourceLocation(),
2937 &Context->Idents.get("arr"),
2938 Context->getPointerType(Context->VoidPtrTy), 0,
2939 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00002940 ICIS_NoInit);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002941 MemberExpr *DictLiteralValueME =
2942 new (Context) MemberExpr(NSValueCallExpr, false, ARRFD,
2943 SourceLocation(),
2944 ARRFD->getType(), VK_LValue,
2945 OK_Ordinary);
2946 QualType ConstIdT = Context->getObjCIdType().withConst();
2947 CStyleCastExpr * DictValueObjects =
2948 NoTypeInfoCStyleCastExpr(Context,
2949 Context->getPointerType(ConstIdT),
2950 CK_BitCast,
2951 DictLiteralValueME);
2952 // (const id <NSCopying> [])keys
2953 Expr *NSKeyCallExpr =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002954 new (Context) CallExpr(*Context, NSDictDRE, KeyExprs,
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002955 NSDictFType, VK_LValue, SourceLocation());
2956
2957 MemberExpr *DictLiteralKeyME =
2958 new (Context) MemberExpr(NSKeyCallExpr, false, ARRFD,
2959 SourceLocation(),
2960 ARRFD->getType(), VK_LValue,
2961 OK_Ordinary);
2962
2963 CStyleCastExpr * DictKeyObjects =
2964 NoTypeInfoCStyleCastExpr(Context,
2965 Context->getPointerType(ConstIdT),
2966 CK_BitCast,
2967 DictLiteralKeyME);
2968
2969
2970
2971 // Synthesize a call to objc_msgSend().
2972 SmallVector<Expr*, 32> MsgExprs;
2973 SmallVector<Expr*, 4> ClsExprs;
2974 QualType argType = Context->getPointerType(Context->CharTy);
2975 QualType expType = Exp->getType();
2976
2977 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2978 ObjCInterfaceDecl *Class =
2979 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2980
2981 IdentifierInfo *clsName = Class->getIdentifier();
2982 ClsExprs.push_back(StringLiteral::Create(*Context,
2983 clsName->getName(),
2984 StringLiteral::Ascii, false,
2985 argType, SourceLocation()));
2986 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2987 &ClsExprs[0],
2988 ClsExprs.size(),
2989 StartLoc, EndLoc);
2990 MsgExprs.push_back(Cls);
2991
2992 // Create a call to sel_registerName("arrayWithObjects:count:").
2993 // it will be the 2nd argument.
2994 SmallVector<Expr*, 4> SelExprs;
2995 ObjCMethodDecl *DictMethod = Exp->getDictWithObjectsMethod();
2996 SelExprs.push_back(StringLiteral::Create(*Context,
2997 DictMethod->getSelector().getAsString(),
2998 StringLiteral::Ascii, false,
2999 argType, SourceLocation()));
3000 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
3001 &SelExprs[0], SelExprs.size(),
3002 StartLoc, EndLoc);
3003 MsgExprs.push_back(SelExp);
3004
3005 // (const id [])objects
3006 MsgExprs.push_back(DictValueObjects);
3007
3008 // (const id <NSCopying> [])keys
3009 MsgExprs.push_back(DictKeyObjects);
3010
3011 // (NSUInteger)cnt
3012 Expr *cnt = IntegerLiteral::Create(*Context,
3013 llvm::APInt(UnsignedIntSize, NumElements),
3014 Context->UnsignedIntTy, SourceLocation());
3015 MsgExprs.push_back(cnt);
3016
3017
3018 SmallVector<QualType, 8> ArgTypes;
3019 ArgTypes.push_back(Context->getObjCIdType());
3020 ArgTypes.push_back(Context->getObjCSelType());
3021 for (ObjCMethodDecl::param_iterator PI = DictMethod->param_begin(),
3022 E = DictMethod->param_end(); PI != E; ++PI) {
3023 QualType T = (*PI)->getType();
3024 if (const PointerType* PT = T->getAs<PointerType>()) {
3025 QualType PointeeTy = PT->getPointeeType();
3026 convertToUnqualifiedObjCType(PointeeTy);
3027 T = Context->getPointerType(PointeeTy);
3028 }
3029 ArgTypes.push_back(T);
3030 }
3031
3032 QualType returnType = Exp->getType();
3033 // Get the type, we will need to reference it in a couple spots.
3034 QualType msgSendType = MsgSendFlavor->getType();
3035
3036 // Create a reference to the objc_msgSend() declaration.
3037 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
3038 VK_LValue, SourceLocation());
3039
3040 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
3041 Context->getPointerType(Context->VoidTy),
3042 CK_BitCast, DRE);
3043
3044 // Now do the "normal" pointer to function cast.
3045 QualType castType =
Jordan Rosebea522f2013-03-08 21:51:21 +00003046 getSimpleFunctionType(returnType, ArgTypes, DictMethod->isVariadic());
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00003047 castType = Context->getPointerType(castType);
3048 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3049 cast);
3050
3051 // Don't forget the parens to enforce the proper binding.
3052 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3053
3054 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003055 CallExpr *CE = new (Context) CallExpr(*Context, PE, MsgExprs,
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00003056 FT->getResultType(), VK_RValue,
3057 EndLoc);
3058 ReplaceStmt(Exp, CE);
3059 return CE;
3060}
3061
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003062// struct __rw_objc_super {
3063// struct objc_object *object; struct objc_object *superClass;
3064// };
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003065QualType RewriteModernObjC::getSuperStructType() {
3066 if (!SuperStructDecl) {
3067 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3068 SourceLocation(), SourceLocation(),
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003069 &Context->Idents.get("__rw_objc_super"));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003070 QualType FieldTypes[2];
3071
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003072 // struct objc_object *object;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003073 FieldTypes[0] = Context->getObjCIdType();
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003074 // struct objc_object *superClass;
3075 FieldTypes[1] = Context->getObjCIdType();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003076
3077 // Create fields
3078 for (unsigned i = 0; i < 2; ++i) {
3079 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
3080 SourceLocation(),
3081 SourceLocation(), 0,
3082 FieldTypes[i], 0,
3083 /*BitWidth=*/0,
3084 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00003085 ICIS_NoInit));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003086 }
3087
3088 SuperStructDecl->completeDefinition();
3089 }
3090 return Context->getTagDeclType(SuperStructDecl);
3091}
3092
3093QualType RewriteModernObjC::getConstantStringStructType() {
3094 if (!ConstantStringDecl) {
3095 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3096 SourceLocation(), SourceLocation(),
3097 &Context->Idents.get("__NSConstantStringImpl"));
3098 QualType FieldTypes[4];
3099
3100 // struct objc_object *receiver;
3101 FieldTypes[0] = Context->getObjCIdType();
3102 // int flags;
3103 FieldTypes[1] = Context->IntTy;
3104 // char *str;
3105 FieldTypes[2] = Context->getPointerType(Context->CharTy);
3106 // long length;
3107 FieldTypes[3] = Context->LongTy;
3108
3109 // Create fields
3110 for (unsigned i = 0; i < 4; ++i) {
3111 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
3112 ConstantStringDecl,
3113 SourceLocation(),
3114 SourceLocation(), 0,
3115 FieldTypes[i], 0,
3116 /*BitWidth=*/0,
3117 /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00003118 ICIS_NoInit));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003119 }
3120
3121 ConstantStringDecl->completeDefinition();
3122 }
3123 return Context->getTagDeclType(ConstantStringDecl);
3124}
3125
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003126/// getFunctionSourceLocation - returns start location of a function
3127/// definition. Complication arises when function has declared as
3128/// extern "C" or extern "C" {...}
3129static SourceLocation getFunctionSourceLocation (RewriteModernObjC &R,
3130 FunctionDecl *FD) {
3131 if (FD->isExternC() && !FD->isMain()) {
3132 const DeclContext *DC = FD->getDeclContext();
3133 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3134 // if it is extern "C" {...}, return function decl's own location.
3135 if (!LSD->getRBraceLoc().isValid())
3136 return LSD->getExternLoc();
3137 }
Rafael Espindola8f187f62013-04-03 15:50:00 +00003138 if (FD->getStorageClass() != SC_None)
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003139 R.RewriteBlockLiteralFunctionDecl(FD);
3140 return FD->getTypeSpecStartLoc();
3141}
3142
Fariborz Jahanian96205962012-11-06 17:30:23 +00003143void RewriteModernObjC::RewriteLineDirective(const Decl *D) {
3144
3145 SourceLocation Location = D->getLocation();
3146
Fariborz Jahanianada71912013-02-08 00:27:34 +00003147 if (Location.isFileID() && GenerateLineInfo) {
Fariborz Jahanian3b45ca92012-11-07 18:15:53 +00003148 std::string LineString("\n#line ");
Fariborz Jahanian96205962012-11-06 17:30:23 +00003149 PresumedLoc PLoc = SM->getPresumedLoc(Location);
3150 LineString += utostr(PLoc.getLine());
3151 LineString += " \"";
NAKAMURA Takumiba529a92012-11-06 22:45:31 +00003152 LineString += Lexer::Stringify(PLoc.getFilename());
Fariborz Jahanian96205962012-11-06 17:30:23 +00003153 if (isa<ObjCMethodDecl>(D))
3154 LineString += "\"";
3155 else LineString += "\"\n";
3156
3157 Location = D->getLocStart();
3158 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3159 if (FD->isExternC() && !FD->isMain()) {
3160 const DeclContext *DC = FD->getDeclContext();
3161 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3162 // if it is extern "C" {...}, return function decl's own location.
3163 if (!LSD->getRBraceLoc().isValid())
3164 Location = LSD->getExternLoc();
3165 }
3166 }
3167 InsertText(Location, LineString);
3168 }
3169}
3170
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003171/// SynthMsgSendStretCallExpr - This routine translates message expression
3172/// into a call to objc_msgSend_stret() entry point. Tricky part is that
3173/// nil check on receiver must be performed before calling objc_msgSend_stret.
3174/// MsgSendStretFlavor - function declaration objc_msgSend_stret(...)
3175/// msgSendType - function type of objc_msgSend_stret(...)
3176/// returnType - Result type of the method being synthesized.
3177/// ArgTypes - type of the arguments passed to objc_msgSend_stret, starting with receiver type.
3178/// MsgExprs - list of argument expressions being passed to objc_msgSend_stret,
3179/// starting with receiver.
3180/// Method - Method being rewritten.
3181Expr *RewriteModernObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
3182 QualType msgSendType,
3183 QualType returnType,
3184 SmallVectorImpl<QualType> &ArgTypes,
3185 SmallVectorImpl<Expr*> &MsgExprs,
3186 ObjCMethodDecl *Method) {
3187 // Now do the "normal" pointer to function cast.
Jordan Rosebea522f2013-03-08 21:51:21 +00003188 QualType castType = getSimpleFunctionType(returnType, ArgTypes,
3189 Method ? Method->isVariadic()
3190 : false);
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003191 castType = Context->getPointerType(castType);
3192
3193 // build type for containing the objc_msgSend_stret object.
3194 static unsigned stretCount=0;
3195 std::string name = "__Stret"; name += utostr(stretCount);
Fariborz Jahanian2ca5af22012-07-25 21:48:36 +00003196 std::string str =
3197 "extern \"C\" void * __cdecl memset(void *_Dst, int _Val, size_t _Size);\n";
3198 str += "struct "; str += name;
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003199 str += " {\n\t";
3200 str += name;
3201 str += "(id receiver, SEL sel";
3202 for (unsigned i = 2; i < ArgTypes.size(); i++) {
Fariborz Jahanian6734ec42012-06-29 19:55:46 +00003203 std::string ArgName = "arg"; ArgName += utostr(i);
3204 ArgTypes[i].getAsStringInternal(ArgName, Context->getPrintingPolicy());
3205 str += ", "; str += ArgName;
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003206 }
3207 // could be vararg.
3208 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
Fariborz Jahanian6734ec42012-06-29 19:55:46 +00003209 std::string ArgName = "arg"; ArgName += utostr(i);
3210 MsgExprs[i]->getType().getAsStringInternal(ArgName,
3211 Context->getPrintingPolicy());
3212 str += ", "; str += ArgName;
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003213 }
3214
3215 str += ") {\n";
3216 str += "\t if (receiver == 0)\n";
3217 str += "\t memset((void*)&s, 0, sizeof(s));\n";
3218 str += "\t else\n";
3219 str += "\t s = (("; str += castType.getAsString(Context->getPrintingPolicy());
3220 str += ")(void *)objc_msgSend_stret)(receiver, sel";
3221 for (unsigned i = 2; i < ArgTypes.size(); i++) {
3222 str += ", arg"; str += utostr(i);
3223 }
3224 // could be vararg.
3225 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3226 str += ", arg"; str += utostr(i);
3227 }
3228
3229 str += ");\n";
3230 str += "\t}\n";
3231 str += "\t"; str += returnType.getAsString(Context->getPrintingPolicy());
3232 str += " s;\n";
3233 str += "};\n\n";
Fariborz Jahaniana6e5a6e2012-08-21 18:56:50 +00003234 SourceLocation FunLocStart;
3235 if (CurFunctionDef)
3236 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
3237 else {
3238 assert(CurMethodDef && "SynthMsgSendStretCallExpr - CurMethodDef is null");
3239 FunLocStart = CurMethodDef->getLocStart();
3240 }
3241
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003242 InsertText(FunLocStart, str);
3243 ++stretCount;
3244
3245 // AST for __Stretn(receiver, args).s;
3246 IdentifierInfo *ID = &Context->Idents.get(name);
3247 FunctionDecl *FD = FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
Chad Rosiere3b29882013-01-04 22:40:33 +00003248 SourceLocation(), ID, castType, 0,
Rafael Espindola8f187f62013-04-03 15:50:00 +00003249 SC_Extern, false, false);
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003250 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, castType, VK_RValue,
3251 SourceLocation());
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003252 CallExpr *STCE = new (Context) CallExpr(*Context, DRE, MsgExprs,
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003253 castType, VK_LValue, SourceLocation());
3254
3255 FieldDecl *FieldD = FieldDecl::Create(*Context, 0, SourceLocation(),
3256 SourceLocation(),
3257 &Context->Idents.get("s"),
3258 returnType, 0,
3259 /*BitWidth=*/0, /*Mutable=*/true,
3260 ICIS_NoInit);
3261 MemberExpr *ME = new (Context) MemberExpr(STCE, false, FieldD, SourceLocation(),
3262 FieldD->getType(), VK_LValue,
3263 OK_Ordinary);
3264
3265 return ME;
3266}
3267
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003268Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
3269 SourceLocation StartLoc,
3270 SourceLocation EndLoc) {
3271 if (!SelGetUidFunctionDecl)
3272 SynthSelGetUidFunctionDecl();
3273 if (!MsgSendFunctionDecl)
3274 SynthMsgSendFunctionDecl();
3275 if (!MsgSendSuperFunctionDecl)
3276 SynthMsgSendSuperFunctionDecl();
3277 if (!MsgSendStretFunctionDecl)
3278 SynthMsgSendStretFunctionDecl();
3279 if (!MsgSendSuperStretFunctionDecl)
3280 SynthMsgSendSuperStretFunctionDecl();
3281 if (!MsgSendFpretFunctionDecl)
3282 SynthMsgSendFpretFunctionDecl();
3283 if (!GetClassFunctionDecl)
3284 SynthGetClassFunctionDecl();
3285 if (!GetSuperClassFunctionDecl)
3286 SynthGetSuperClassFunctionDecl();
3287 if (!GetMetaClassFunctionDecl)
3288 SynthGetMetaClassFunctionDecl();
3289
3290 // default to objc_msgSend().
3291 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
3292 // May need to use objc_msgSend_stret() as well.
3293 FunctionDecl *MsgSendStretFlavor = 0;
3294 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
3295 QualType resultType = mDecl->getResultType();
3296 if (resultType->isRecordType())
3297 MsgSendStretFlavor = MsgSendStretFunctionDecl;
3298 else if (resultType->isRealFloatingType())
3299 MsgSendFlavor = MsgSendFpretFunctionDecl;
3300 }
3301
3302 // Synthesize a call to objc_msgSend().
3303 SmallVector<Expr*, 8> MsgExprs;
3304 switch (Exp->getReceiverKind()) {
3305 case ObjCMessageExpr::SuperClass: {
3306 MsgSendFlavor = MsgSendSuperFunctionDecl;
3307 if (MsgSendStretFlavor)
3308 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3309 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3310
3311 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3312
3313 SmallVector<Expr*, 4> InitExprs;
3314
3315 // set the receiver to self, the first argument to all methods.
3316 InitExprs.push_back(
3317 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3318 CK_BitCast,
3319 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00003320 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003321 Context->getObjCIdType(),
3322 VK_RValue,
3323 SourceLocation()))
3324 ); // set the 'receiver'.
3325
3326 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3327 SmallVector<Expr*, 8> ClsExprs;
3328 QualType argType = Context->getPointerType(Context->CharTy);
3329 ClsExprs.push_back(StringLiteral::Create(*Context,
3330 ClassDecl->getIdentifier()->getName(),
3331 StringLiteral::Ascii, false,
3332 argType, SourceLocation()));
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003333 // (Class)objc_getClass("CurrentClass")
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003334 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
3335 &ClsExprs[0],
3336 ClsExprs.size(),
3337 StartLoc,
3338 EndLoc);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003339 ClsExprs.clear();
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003340 ClsExprs.push_back(Cls);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003341 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3342 &ClsExprs[0], ClsExprs.size(),
3343 StartLoc, EndLoc);
3344
3345 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3346 // To turn off a warning, type-cast to 'id'
3347 InitExprs.push_back( // set 'super class', using class_getSuperclass().
3348 NoTypeInfoCStyleCastExpr(Context,
3349 Context->getObjCIdType(),
3350 CK_BitCast, Cls));
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003351 // struct __rw_objc_super
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003352 QualType superType = getSuperStructType();
3353 Expr *SuperRep;
3354
3355 if (LangOpts.MicrosoftExt) {
3356 SynthSuperContructorFunctionDecl();
3357 // Simulate a contructor call...
3358 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00003359 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003360 SourceLocation());
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003361 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003362 superType, VK_LValue,
3363 SourceLocation());
3364 // The code for super is a little tricky to prevent collision with
3365 // the structure definition in the header. The rewriter has it's own
3366 // internal definition (__rw_objc_super) that is uses. This is why
3367 // we need the cast below. For example:
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003368 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003369 //
3370 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3371 Context->getPointerType(SuperRep->getType()),
3372 VK_RValue, OK_Ordinary,
3373 SourceLocation());
3374 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3375 Context->getPointerType(superType),
3376 CK_BitCast, SuperRep);
3377 } else {
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003378 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003379 InitListExpr *ILE =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003380 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003381 SourceLocation());
3382 TypeSourceInfo *superTInfo
3383 = Context->getTrivialTypeSourceInfo(superType);
3384 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3385 superType, VK_LValue,
3386 ILE, false);
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003387 // struct __rw_objc_super *
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003388 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3389 Context->getPointerType(SuperRep->getType()),
3390 VK_RValue, OK_Ordinary,
3391 SourceLocation());
3392 }
3393 MsgExprs.push_back(SuperRep);
3394 break;
3395 }
3396
3397 case ObjCMessageExpr::Class: {
3398 SmallVector<Expr*, 8> ClsExprs;
3399 QualType argType = Context->getPointerType(Context->CharTy);
3400 ObjCInterfaceDecl *Class
3401 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
3402 IdentifierInfo *clsName = Class->getIdentifier();
3403 ClsExprs.push_back(StringLiteral::Create(*Context,
3404 clsName->getName(),
3405 StringLiteral::Ascii, false,
3406 argType, SourceLocation()));
3407 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3408 &ClsExprs[0],
3409 ClsExprs.size(),
3410 StartLoc, EndLoc);
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003411 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
3412 Context->getObjCIdType(),
3413 CK_BitCast, Cls);
3414 MsgExprs.push_back(ArgExpr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003415 break;
3416 }
3417
3418 case ObjCMessageExpr::SuperInstance:{
3419 MsgSendFlavor = MsgSendSuperFunctionDecl;
3420 if (MsgSendStretFlavor)
3421 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3422 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3423 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3424 SmallVector<Expr*, 4> InitExprs;
3425
3426 InitExprs.push_back(
3427 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3428 CK_BitCast,
3429 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00003430 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003431 Context->getObjCIdType(),
3432 VK_RValue, SourceLocation()))
3433 ); // set the 'receiver'.
3434
3435 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3436 SmallVector<Expr*, 8> ClsExprs;
3437 QualType argType = Context->getPointerType(Context->CharTy);
3438 ClsExprs.push_back(StringLiteral::Create(*Context,
3439 ClassDecl->getIdentifier()->getName(),
3440 StringLiteral::Ascii, false, argType,
3441 SourceLocation()));
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003442 // (Class)objc_getClass("CurrentClass")
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003443 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3444 &ClsExprs[0],
3445 ClsExprs.size(),
3446 StartLoc, EndLoc);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003447 ClsExprs.clear();
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003448 ClsExprs.push_back(Cls);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003449 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3450 &ClsExprs[0], ClsExprs.size(),
3451 StartLoc, EndLoc);
3452
3453 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3454 // To turn off a warning, type-cast to 'id'
3455 InitExprs.push_back(
3456 // set 'super class', using class_getSuperclass().
3457 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3458 CK_BitCast, Cls));
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003459 // struct __rw_objc_super
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003460 QualType superType = getSuperStructType();
3461 Expr *SuperRep;
3462
3463 if (LangOpts.MicrosoftExt) {
3464 SynthSuperContructorFunctionDecl();
3465 // Simulate a contructor call...
3466 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00003467 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003468 SourceLocation());
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003469 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003470 superType, VK_LValue, SourceLocation());
3471 // The code for super is a little tricky to prevent collision with
3472 // the structure definition in the header. The rewriter has it's own
3473 // internal definition (__rw_objc_super) that is uses. This is why
3474 // we need the cast below. For example:
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003475 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003476 //
3477 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3478 Context->getPointerType(SuperRep->getType()),
3479 VK_RValue, OK_Ordinary,
3480 SourceLocation());
3481 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3482 Context->getPointerType(superType),
3483 CK_BitCast, SuperRep);
3484 } else {
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003485 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003486 InitListExpr *ILE =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003487 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003488 SourceLocation());
3489 TypeSourceInfo *superTInfo
3490 = Context->getTrivialTypeSourceInfo(superType);
3491 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3492 superType, VK_RValue, ILE,
3493 false);
3494 }
3495 MsgExprs.push_back(SuperRep);
3496 break;
3497 }
3498
3499 case ObjCMessageExpr::Instance: {
3500 // Remove all type-casts because it may contain objc-style types; e.g.
3501 // Foo<Proto> *.
3502 Expr *recExpr = Exp->getInstanceReceiver();
3503 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
3504 recExpr = CE->getSubExpr();
3505 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
3506 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
3507 ? CK_BlockPointerToObjCPointerCast
3508 : CK_CPointerToObjCPointerCast;
3509
3510 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3511 CK, recExpr);
3512 MsgExprs.push_back(recExpr);
3513 break;
3514 }
3515 }
3516
3517 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
3518 SmallVector<Expr*, 8> SelExprs;
3519 QualType argType = Context->getPointerType(Context->CharTy);
3520 SelExprs.push_back(StringLiteral::Create(*Context,
3521 Exp->getSelector().getAsString(),
3522 StringLiteral::Ascii, false,
3523 argType, SourceLocation()));
3524 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
3525 &SelExprs[0], SelExprs.size(),
3526 StartLoc,
3527 EndLoc);
3528 MsgExprs.push_back(SelExp);
3529
3530 // Now push any user supplied arguments.
3531 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
3532 Expr *userExpr = Exp->getArg(i);
3533 // Make all implicit casts explicit...ICE comes in handy:-)
3534 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
3535 // Reuse the ICE type, it is exactly what the doctor ordered.
3536 QualType type = ICE->getType();
3537 if (needToScanForQualifiers(type))
3538 type = Context->getObjCIdType();
3539 // Make sure we convert "type (^)(...)" to "type (*)(...)".
3540 (void)convertBlockPointerToFunctionPointer(type);
3541 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
3542 CastKind CK;
3543 if (SubExpr->getType()->isIntegralType(*Context) &&
3544 type->isBooleanType()) {
3545 CK = CK_IntegralToBoolean;
3546 } else if (type->isObjCObjectPointerType()) {
3547 if (SubExpr->getType()->isBlockPointerType()) {
3548 CK = CK_BlockPointerToObjCPointerCast;
3549 } else if (SubExpr->getType()->isPointerType()) {
3550 CK = CK_CPointerToObjCPointerCast;
3551 } else {
3552 CK = CK_BitCast;
3553 }
3554 } else {
3555 CK = CK_BitCast;
3556 }
3557
3558 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
3559 }
3560 // Make id<P...> cast into an 'id' cast.
3561 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
3562 if (CE->getType()->isObjCQualifiedIdType()) {
3563 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
3564 userExpr = CE->getSubExpr();
3565 CastKind CK;
3566 if (userExpr->getType()->isIntegralType(*Context)) {
3567 CK = CK_IntegralToPointer;
3568 } else if (userExpr->getType()->isBlockPointerType()) {
3569 CK = CK_BlockPointerToObjCPointerCast;
3570 } else if (userExpr->getType()->isPointerType()) {
3571 CK = CK_CPointerToObjCPointerCast;
3572 } else {
3573 CK = CK_BitCast;
3574 }
3575 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3576 CK, userExpr);
3577 }
3578 }
3579 MsgExprs.push_back(userExpr);
3580 // We've transferred the ownership to MsgExprs. For now, we *don't* null
3581 // out the argument in the original expression (since we aren't deleting
3582 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
3583 //Exp->setArg(i, 0);
3584 }
3585 // Generate the funky cast.
3586 CastExpr *cast;
3587 SmallVector<QualType, 8> ArgTypes;
3588 QualType returnType;
3589
3590 // Push 'id' and 'SEL', the 2 implicit arguments.
3591 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3592 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3593 else
3594 ArgTypes.push_back(Context->getObjCIdType());
3595 ArgTypes.push_back(Context->getObjCSelType());
3596 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
3597 // Push any user argument types.
3598 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
3599 E = OMD->param_end(); PI != E; ++PI) {
3600 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
3601 ? Context->getObjCIdType()
3602 : (*PI)->getType();
3603 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3604 (void)convertBlockPointerToFunctionPointer(t);
3605 ArgTypes.push_back(t);
3606 }
3607 returnType = Exp->getType();
3608 convertToUnqualifiedObjCType(returnType);
3609 (void)convertBlockPointerToFunctionPointer(returnType);
3610 } else {
3611 returnType = Context->getObjCIdType();
3612 }
3613 // Get the type, we will need to reference it in a couple spots.
3614 QualType msgSendType = MsgSendFlavor->getType();
3615
3616 // Create a reference to the objc_msgSend() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00003617 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003618 VK_LValue, SourceLocation());
3619
3620 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
3621 // If we don't do this cast, we get the following bizarre warning/note:
3622 // xx.m:13: warning: function called through a non-compatible type
3623 // xx.m:13: note: if this code is reached, the program will abort
3624 cast = NoTypeInfoCStyleCastExpr(Context,
3625 Context->getPointerType(Context->VoidTy),
3626 CK_BitCast, DRE);
3627
3628 // Now do the "normal" pointer to function cast.
Jordan Rosebea522f2013-03-08 21:51:21 +00003629 // If we don't have a method decl, force a variadic cast.
3630 const ObjCMethodDecl *MD = Exp->getMethodDecl();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003631 QualType castType =
Jordan Rosebea522f2013-03-08 21:51:21 +00003632 getSimpleFunctionType(returnType, ArgTypes, MD ? MD->isVariadic() : true);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003633 castType = Context->getPointerType(castType);
3634 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3635 cast);
3636
3637 // Don't forget the parens to enforce the proper binding.
3638 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3639
3640 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003641 CallExpr *CE = new (Context) CallExpr(*Context, PE, MsgExprs,
3642 FT->getResultType(), VK_RValue, EndLoc);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003643 Stmt *ReplacingStmt = CE;
3644 if (MsgSendStretFlavor) {
3645 // We have the method which returns a struct/union. Must also generate
3646 // call to objc_msgSend_stret and hang both varieties on a conditional
3647 // expression which dictate which one to envoke depending on size of
3648 // method's return type.
3649
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003650 Expr *STCE = SynthMsgSendStretCallExpr(MsgSendStretFlavor,
3651 msgSendType, returnType,
3652 ArgTypes, MsgExprs,
3653 Exp->getMethodDecl());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003654
3655 // Build sizeof(returnType)
3656 UnaryExprOrTypeTraitExpr *sizeofExpr =
3657 new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
3658 Context->getTrivialTypeSourceInfo(returnType),
3659 Context->getSizeType(), SourceLocation(),
3660 SourceLocation());
3661 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3662 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3663 // For X86 it is more complicated and some kind of target specific routine
3664 // is needed to decide what to do.
3665 unsigned IntSize =
3666 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
3667 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3668 llvm::APInt(IntSize, 8),
3669 Context->IntTy,
3670 SourceLocation());
3671 BinaryOperator *lessThanExpr =
3672 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
Lang Hamesbe9af122012-10-02 04:45:10 +00003673 VK_RValue, OK_Ordinary, SourceLocation(),
3674 false);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003675 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3676 ConditionalOperator *CondExpr =
3677 new (Context) ConditionalOperator(lessThanExpr,
3678 SourceLocation(), CE,
3679 SourceLocation(), STCE,
3680 returnType, VK_RValue, OK_Ordinary);
3681 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3682 CondExpr);
3683 }
3684 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3685 return ReplacingStmt;
3686}
3687
3688Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
3689 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3690 Exp->getLocEnd());
3691
3692 // Now do the actual rewrite.
3693 ReplaceStmt(Exp, ReplacingStmt);
3694
3695 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3696 return ReplacingStmt;
3697}
3698
3699// typedef struct objc_object Protocol;
3700QualType RewriteModernObjC::getProtocolType() {
3701 if (!ProtocolTypeDecl) {
3702 TypeSourceInfo *TInfo
3703 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3704 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
3705 SourceLocation(), SourceLocation(),
3706 &Context->Idents.get("Protocol"),
3707 TInfo);
3708 }
3709 return Context->getTypeDeclType(ProtocolTypeDecl);
3710}
3711
3712/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3713/// a synthesized/forward data reference (to the protocol's metadata).
3714/// The forward references (and metadata) are generated in
3715/// RewriteModernObjC::HandleTranslationUnit().
3716Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00003717 std::string Name = "_OBJC_PROTOCOL_REFERENCE_$_" +
3718 Exp->getProtocol()->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003719 IdentifierInfo *ID = &Context->Idents.get(Name);
3720 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
3721 SourceLocation(), ID, getProtocolType(), 0,
Rafael Espindola8f187f62013-04-03 15:50:00 +00003722 SC_Extern);
John McCallf4b88a42012-03-10 09:33:50 +00003723 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
3724 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003725 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
3726 Context->getPointerType(DRE->getType()),
3727 VK_RValue, OK_Ordinary, SourceLocation());
3728 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
3729 CK_BitCast,
3730 DerefExpr);
3731 ReplaceStmt(Exp, castExpr);
3732 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3733 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3734 return castExpr;
3735
3736}
3737
3738bool RewriteModernObjC::BufferContainsPPDirectives(const char *startBuf,
3739 const char *endBuf) {
3740 while (startBuf < endBuf) {
3741 if (*startBuf == '#') {
3742 // Skip whitespace.
3743 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3744 ;
3745 if (!strncmp(startBuf, "if", strlen("if")) ||
3746 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3747 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3748 !strncmp(startBuf, "define", strlen("define")) ||
3749 !strncmp(startBuf, "undef", strlen("undef")) ||
3750 !strncmp(startBuf, "else", strlen("else")) ||
3751 !strncmp(startBuf, "elif", strlen("elif")) ||
3752 !strncmp(startBuf, "endif", strlen("endif")) ||
3753 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3754 !strncmp(startBuf, "include", strlen("include")) ||
3755 !strncmp(startBuf, "import", strlen("import")) ||
3756 !strncmp(startBuf, "include_next", strlen("include_next")))
3757 return true;
3758 }
3759 startBuf++;
3760 }
3761 return false;
3762}
3763
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003764/// IsTagDefinedInsideClass - This routine checks that a named tagged type
3765/// is defined inside an objective-c class. If so, it returns true.
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00003766bool RewriteModernObjC::IsTagDefinedInsideClass(ObjCContainerDecl *IDecl,
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003767 TagDecl *Tag,
3768 bool &IsNamedDefinition) {
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003769 if (!IDecl)
3770 return false;
3771 SourceLocation TagLocation;
3772 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) {
3773 RD = RD->getDefinition();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003774 if (!RD || !RD->getDeclName().getAsIdentifierInfo())
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003775 return false;
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003776 IsNamedDefinition = true;
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003777 TagLocation = RD->getLocation();
3778 return Context->getSourceManager().isBeforeInTranslationUnit(
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003779 IDecl->getLocation(), TagLocation);
3780 }
3781 if (EnumDecl *ED = dyn_cast<EnumDecl>(Tag)) {
3782 if (!ED || !ED->getDeclName().getAsIdentifierInfo())
3783 return false;
3784 IsNamedDefinition = true;
3785 TagLocation = ED->getLocation();
3786 return Context->getSourceManager().isBeforeInTranslationUnit(
3787 IDecl->getLocation(), TagLocation);
3788
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003789 }
3790 return false;
3791}
3792
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003793/// RewriteObjCFieldDeclType - This routine rewrites a type into the buffer.
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003794/// It handles elaborated types, as well as enum types in the process.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003795bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type,
3796 std::string &Result) {
Fariborz Jahanianf5eac482012-05-02 17:34:59 +00003797 if (isa<TypedefType>(Type)) {
3798 Result += "\t";
3799 return false;
3800 }
3801
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003802 if (Type->isArrayType()) {
3803 QualType ElemTy = Context->getBaseElementType(Type);
3804 return RewriteObjCFieldDeclType(ElemTy, Result);
3805 }
3806 else if (Type->isRecordType()) {
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003807 RecordDecl *RD = Type->getAs<RecordType>()->getDecl();
3808 if (RD->isCompleteDefinition()) {
3809 if (RD->isStruct())
3810 Result += "\n\tstruct ";
3811 else if (RD->isUnion())
3812 Result += "\n\tunion ";
3813 else
3814 assert(false && "class not allowed as an ivar type");
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003815
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003816 Result += RD->getName();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003817 if (GlobalDefinedTags.count(RD)) {
3818 // struct/union is defined globally, use it.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003819 Result += " ";
3820 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003821 }
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003822 Result += " {\n";
3823 for (RecordDecl::field_iterator i = RD->field_begin(),
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003824 e = RD->field_end(); i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00003825 FieldDecl *FD = *i;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003826 RewriteObjCFieldDecl(FD, Result);
3827 }
3828 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003829 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003830 }
3831 }
3832 else if (Type->isEnumeralType()) {
3833 EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3834 if (ED->isCompleteDefinition()) {
3835 Result += "\n\tenum ";
3836 Result += ED->getName();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003837 if (GlobalDefinedTags.count(ED)) {
3838 // Enum is globall defined, use it.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003839 Result += " ";
3840 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003841 }
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003842
3843 Result += " {\n";
3844 for (EnumDecl::enumerator_iterator EC = ED->enumerator_begin(),
3845 ECEnd = ED->enumerator_end(); EC != ECEnd; ++EC) {
3846 Result += "\t"; Result += EC->getName(); Result += " = ";
3847 llvm::APSInt Val = EC->getInitVal();
3848 Result += Val.toString(10);
3849 Result += ",\n";
3850 }
3851 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003852 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003853 }
3854 }
3855
3856 Result += "\t";
3857 convertObjCTypeToCStyleType(Type);
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003858 return false;
3859}
3860
3861
3862/// RewriteObjCFieldDecl - This routine rewrites a field into the buffer.
3863/// It handles elaborated types, as well as enum types in the process.
3864void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl,
3865 std::string &Result) {
3866 QualType Type = fieldDecl->getType();
3867 std::string Name = fieldDecl->getNameAsString();
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003868
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003869 bool EleboratedType = RewriteObjCFieldDeclType(Type, Result);
3870 if (!EleboratedType)
3871 Type.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003872 Result += Name;
3873 if (fieldDecl->isBitField()) {
3874 Result += " : "; Result += utostr(fieldDecl->getBitWidthValue(*Context));
3875 }
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003876 else if (EleboratedType && Type->isArrayType()) {
Eli Friedman6febf122012-12-13 01:43:21 +00003877 const ArrayType *AT = Context->getAsArrayType(Type);
3878 do {
3879 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003880 Result += "[";
3881 llvm::APInt Dim = CAT->getSize();
3882 Result += utostr(Dim.getZExtValue());
3883 Result += "]";
3884 }
Eli Friedman6febf122012-12-13 01:43:21 +00003885 AT = Context->getAsArrayType(AT->getElementType());
3886 } while (AT);
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003887 }
3888
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003889 Result += ";\n";
3890}
3891
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003892/// RewriteLocallyDefinedNamedAggregates - This routine rewrites locally defined
3893/// named aggregate types into the input buffer.
3894void RewriteModernObjC::RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
3895 std::string &Result) {
3896 QualType Type = fieldDecl->getType();
Fariborz Jahanianf5eac482012-05-02 17:34:59 +00003897 if (isa<TypedefType>(Type))
3898 return;
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003899 if (Type->isArrayType())
3900 Type = Context->getBaseElementType(Type);
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00003901 ObjCContainerDecl *IDecl =
3902 dyn_cast<ObjCContainerDecl>(fieldDecl->getDeclContext());
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003903
3904 TagDecl *TD = 0;
3905 if (Type->isRecordType()) {
3906 TD = Type->getAs<RecordType>()->getDecl();
3907 }
3908 else if (Type->isEnumeralType()) {
3909 TD = Type->getAs<EnumType>()->getDecl();
3910 }
3911
3912 if (TD) {
3913 if (GlobalDefinedTags.count(TD))
3914 return;
3915
3916 bool IsNamedDefinition = false;
3917 if (IsTagDefinedInsideClass(IDecl, TD, IsNamedDefinition)) {
3918 RewriteObjCFieldDeclType(Type, Result);
3919 Result += ";";
3920 }
3921 if (IsNamedDefinition)
3922 GlobalDefinedTags.insert(TD);
3923 }
3924
3925}
3926
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00003927unsigned RewriteModernObjC::ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV) {
3928 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3929 if (ObjCInterefaceHasBitfieldGroups.count(CDecl)) {
3930 return IvarGroupNumber[IV];
3931 }
3932 unsigned GroupNo = 0;
3933 SmallVector<const ObjCIvarDecl *, 8> IVars;
3934 for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3935 IVD; IVD = IVD->getNextIvar())
3936 IVars.push_back(IVD);
3937
3938 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3939 if (IVars[i]->isBitField()) {
3940 IvarGroupNumber[IVars[i++]] = ++GroupNo;
3941 while (i < e && IVars[i]->isBitField())
3942 IvarGroupNumber[IVars[i++]] = GroupNo;
3943 if (i < e)
3944 --i;
3945 }
3946
3947 ObjCInterefaceHasBitfieldGroups.insert(CDecl);
3948 return IvarGroupNumber[IV];
3949}
3950
3951QualType RewriteModernObjC::SynthesizeBitfieldGroupStructType(
3952 ObjCIvarDecl *IV,
3953 SmallVectorImpl<ObjCIvarDecl *> &IVars) {
3954 std::string StructTagName;
3955 ObjCIvarBitfieldGroupType(IV, StructTagName);
3956 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct,
3957 Context->getTranslationUnitDecl(),
3958 SourceLocation(), SourceLocation(),
3959 &Context->Idents.get(StructTagName));
3960 for (unsigned i=0, e = IVars.size(); i < e; i++) {
3961 ObjCIvarDecl *Ivar = IVars[i];
3962 RD->addDecl(FieldDecl::Create(*Context, RD, SourceLocation(), SourceLocation(),
3963 &Context->Idents.get(Ivar->getName()),
3964 Ivar->getType(),
3965 0, /*Expr *BW */Ivar->getBitWidth(), false,
3966 ICIS_NoInit));
3967 }
3968 RD->completeDefinition();
3969 return Context->getTagDeclType(RD);
3970}
3971
3972QualType RewriteModernObjC::GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl *IV) {
3973 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3974 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3975 std::pair<const ObjCInterfaceDecl*, unsigned> tuple = std::make_pair(CDecl, GroupNo);
3976 if (GroupRecordType.count(tuple))
3977 return GroupRecordType[tuple];
3978
3979 SmallVector<ObjCIvarDecl *, 8> IVars;
3980 for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3981 IVD; IVD = IVD->getNextIvar()) {
3982 if (IVD->isBitField())
3983 IVars.push_back(const_cast<ObjCIvarDecl *>(IVD));
3984 else {
3985 if (!IVars.empty()) {
3986 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
3987 // Generate the struct type for this group of bitfield ivars.
3988 GroupRecordType[std::make_pair(CDecl, GroupNo)] =
3989 SynthesizeBitfieldGroupStructType(IVars[0], IVars);
3990 IVars.clear();
3991 }
3992 }
3993 }
3994 if (!IVars.empty()) {
3995 // Do the last one.
3996 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
3997 GroupRecordType[std::make_pair(CDecl, GroupNo)] =
3998 SynthesizeBitfieldGroupStructType(IVars[0], IVars);
3999 }
4000 QualType RetQT = GroupRecordType[tuple];
4001 assert(!RetQT.isNull() && "GetGroupRecordTypeForObjCIvarBitfield struct type is NULL");
4002
4003 return RetQT;
4004}
4005
4006/// ObjCIvarBitfieldGroupDecl - Names field decl. for ivar bitfield group.
4007/// Name would be: classname__GRBF_n where n is the group number for this ivar.
4008void RewriteModernObjC::ObjCIvarBitfieldGroupDecl(ObjCIvarDecl *IV,
4009 std::string &Result) {
4010 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
4011 Result += CDecl->getName();
4012 Result += "__GRBF_";
4013 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
4014 Result += utostr(GroupNo);
4015 return;
4016}
4017
4018/// ObjCIvarBitfieldGroupType - Names struct type for ivar bitfield group.
4019/// Name of the struct would be: classname__T_n where n is the group number for
4020/// this ivar.
4021void RewriteModernObjC::ObjCIvarBitfieldGroupType(ObjCIvarDecl *IV,
4022 std::string &Result) {
4023 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
4024 Result += CDecl->getName();
4025 Result += "__T_";
4026 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
4027 Result += utostr(GroupNo);
4028 return;
4029}
4030
4031/// ObjCIvarBitfieldGroupOffset - Names symbol for ivar bitfield group field offset.
4032/// Name would be: OBJC_IVAR_$_classname__GRBF_n where n is the group number for
4033/// this ivar.
4034void RewriteModernObjC::ObjCIvarBitfieldGroupOffset(ObjCIvarDecl *IV,
4035 std::string &Result) {
4036 Result += "OBJC_IVAR_$_";
4037 ObjCIvarBitfieldGroupDecl(IV, Result);
4038}
4039
4040#define SKIP_BITFIELDS(IX, ENDIX, VEC) { \
4041 while ((IX < ENDIX) && VEC[IX]->isBitField()) \
4042 ++IX; \
4043 if (IX < ENDIX) \
4044 --IX; \
4045}
4046
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004047/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
4048/// an objective-c class with ivars.
4049void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
4050 std::string &Result) {
4051 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
4052 assert(CDecl->getName() != "" &&
4053 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004054 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00004055 SmallVector<ObjCIvarDecl *, 8> IVars;
4056 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00004057 IVD; IVD = IVD->getNextIvar())
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00004058 IVars.push_back(IVD);
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00004059
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004060 SourceLocation LocStart = CDecl->getLocStart();
4061 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00004062
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004063 const char *startBuf = SM->getCharacterData(LocStart);
4064 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00004065
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004066 // If no ivars and no root or if its root, directly or indirectly,
4067 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00004068 if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) &&
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004069 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
4070 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
4071 ReplaceText(LocStart, endBuf-startBuf, Result);
4072 return;
4073 }
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00004074
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00004075 // Insert named struct/union definitions inside class to
4076 // outer scope. This follows semantics of locally defined
4077 // struct/unions in objective-c classes.
4078 for (unsigned i = 0, e = IVars.size(); i < e; i++)
4079 RewriteLocallyDefinedNamedAggregates(IVars[i], Result);
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00004080
4081 // Insert named structs which are syntheized to group ivar bitfields
4082 // to outer scope as well.
4083 for (unsigned i = 0, e = IVars.size(); i < e; i++)
4084 if (IVars[i]->isBitField()) {
4085 ObjCIvarDecl *IV = IVars[i];
4086 QualType QT = GetGroupRecordTypeForObjCIvarBitfield(IV);
4087 RewriteObjCFieldDeclType(QT, Result);
4088 Result += ";";
4089 // skip over ivar bitfields in this group.
4090 SKIP_BITFIELDS(i , e, IVars);
4091 }
4092
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004093 Result += "\nstruct ";
4094 Result += CDecl->getNameAsString();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00004095 Result += "_IMPL {\n";
4096
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00004097 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00004098 Result += "\tstruct "; Result += RCDecl->getNameAsString();
4099 Result += "_IMPL "; Result += RCDecl->getNameAsString();
4100 Result += "_IVARS;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004101 }
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00004102
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00004103 for (unsigned i = 0, e = IVars.size(); i < e; i++) {
4104 if (IVars[i]->isBitField()) {
4105 ObjCIvarDecl *IV = IVars[i];
4106 Result += "\tstruct ";
4107 ObjCIvarBitfieldGroupType(IV, Result); Result += " ";
4108 ObjCIvarBitfieldGroupDecl(IV, Result); Result += ";\n";
4109 // skip over ivar bitfields in this group.
4110 SKIP_BITFIELDS(i , e, IVars);
4111 }
4112 else
4113 RewriteObjCFieldDecl(IVars[i], Result);
4114 }
Fariborz Jahanian0b17b9a2012-02-12 21:36:23 +00004115
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00004116 Result += "};\n";
4117 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
4118 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00004119 // Mark this struct as having been generated.
4120 if (!ObjCSynthesizedStructs.insert(CDecl))
4121 llvm_unreachable("struct already synthesize- RewriteObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004122}
4123
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00004124/// RewriteIvarOffsetSymbols - Rewrite ivar offset symbols of those ivars which
4125/// have been referenced in an ivar access expression.
4126void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
4127 std::string &Result) {
4128 // write out ivar offset symbols which have been referenced in an ivar
4129 // access expression.
4130 llvm::SmallPtrSet<ObjCIvarDecl *, 8> Ivars = ReferencedIvars[CDecl];
4131 if (Ivars.empty())
4132 return;
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00004133
4134 llvm::DenseSet<std::pair<const ObjCInterfaceDecl*, unsigned> > GroupSymbolOutput;
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00004135 for (llvm::SmallPtrSet<ObjCIvarDecl *, 8>::iterator i = Ivars.begin(),
4136 e = Ivars.end(); i != e; i++) {
4137 ObjCIvarDecl *IvarDecl = (*i);
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00004138 const ObjCInterfaceDecl *IDecl = IvarDecl->getContainingInterface();
4139 unsigned GroupNo = 0;
4140 if (IvarDecl->isBitField()) {
4141 GroupNo = ObjCIvarBitfieldGroupNo(IvarDecl);
4142 if (GroupSymbolOutput.count(std::make_pair(IDecl, GroupNo)))
4143 continue;
4144 }
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00004145 Result += "\n";
4146 if (LangOpts.MicrosoftExt)
4147 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00004148 Result += "extern \"C\" ";
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00004149 if (LangOpts.MicrosoftExt &&
4150 IvarDecl->getAccessControl() != ObjCIvarDecl::Private &&
Fariborz Jahanian297976d2012-03-29 17:51:09 +00004151 IvarDecl->getAccessControl() != ObjCIvarDecl::Package)
4152 Result += "__declspec(dllimport) ";
4153
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00004154 Result += "unsigned long ";
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00004155 if (IvarDecl->isBitField()) {
4156 ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
4157 GroupSymbolOutput.insert(std::make_pair(IDecl, GroupNo));
4158 }
4159 else
4160 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00004161 Result += ";";
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00004162 }
4163}
4164
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004165//===----------------------------------------------------------------------===//
4166// Meta Data Emission
4167//===----------------------------------------------------------------------===//
4168
4169
4170/// RewriteImplementations - This routine rewrites all method implementations
4171/// and emits meta-data.
4172
4173void RewriteModernObjC::RewriteImplementations() {
4174 int ClsDefCount = ClassImplementation.size();
4175 int CatDefCount = CategoryImplementation.size();
4176
4177 // Rewrite implemented methods
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00004178 for (int i = 0; i < ClsDefCount; i++) {
4179 ObjCImplementationDecl *OIMP = ClassImplementation[i];
4180 ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
4181 if (CDecl->isImplicitInterfaceDecl())
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00004182 assert(false &&
4183 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00004184 RewriteImplementationDecl(OIMP);
4185 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004186
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00004187 for (int i = 0; i < CatDefCount; i++) {
4188 ObjCCategoryImplDecl *CIMP = CategoryImplementation[i];
4189 ObjCInterfaceDecl *CDecl = CIMP->getClassInterface();
4190 if (CDecl->isImplicitInterfaceDecl())
4191 assert(false &&
4192 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00004193 RewriteImplementationDecl(CIMP);
4194 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004195}
4196
4197void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
4198 const std::string &Name,
4199 ValueDecl *VD, bool def) {
4200 assert(BlockByRefDeclNo.count(VD) &&
4201 "RewriteByRefString: ByRef decl missing");
4202 if (def)
4203 ResultStr += "struct ";
4204 ResultStr += "__Block_byref_" + Name +
4205 "_" + utostr(BlockByRefDeclNo[VD]) ;
4206}
4207
4208static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
4209 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4210 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
4211 return false;
4212}
4213
4214std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
4215 StringRef funcName,
4216 std::string Tag) {
4217 const FunctionType *AFT = CE->getFunctionType();
4218 QualType RT = AFT->getResultType();
4219 std::string StructRef = "struct " + Tag;
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00004220 SourceLocation BlockLoc = CE->getExprLoc();
4221 std::string S;
4222 ConvertSourceLocationToLineDirective(BlockLoc, S);
4223
4224 S += "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
4225 funcName.str() + "_block_func_" + utostr(i);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004226
4227 BlockDecl *BD = CE->getBlockDecl();
4228
4229 if (isa<FunctionNoProtoType>(AFT)) {
4230 // No user-supplied arguments. Still need to pass in a pointer to the
4231 // block (to reference imported block decl refs).
4232 S += "(" + StructRef + " *__cself)";
4233 } else if (BD->param_empty()) {
4234 S += "(" + StructRef + " *__cself)";
4235 } else {
4236 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
4237 assert(FT && "SynthesizeBlockFunc: No function proto");
4238 S += '(';
4239 // first add the implicit argument.
4240 S += StructRef + " *__cself, ";
4241 std::string ParamStr;
4242 for (BlockDecl::param_iterator AI = BD->param_begin(),
4243 E = BD->param_end(); AI != E; ++AI) {
4244 if (AI != BD->param_begin()) S += ", ";
4245 ParamStr = (*AI)->getNameAsString();
4246 QualType QT = (*AI)->getType();
Fariborz Jahanian2610f902012-03-27 16:42:20 +00004247 (void)convertBlockPointerToFunctionPointer(QT);
4248 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004249 S += ParamStr;
4250 }
4251 if (FT->isVariadic()) {
4252 if (!BD->param_empty()) S += ", ";
4253 S += "...";
4254 }
4255 S += ')';
4256 }
4257 S += " {\n";
4258
4259 // Create local declarations to avoid rewriting all closure decl ref exprs.
4260 // First, emit a declaration for all "by ref" decls.
4261 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4262 E = BlockByRefDecls.end(); I != E; ++I) {
4263 S += " ";
4264 std::string Name = (*I)->getNameAsString();
4265 std::string TypeString;
4266 RewriteByRefString(TypeString, Name, (*I));
4267 TypeString += " *";
4268 Name = TypeString + Name;
4269 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
4270 }
4271 // Next, emit a declaration for all "by copy" declarations.
4272 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4273 E = BlockByCopyDecls.end(); I != E; ++I) {
4274 S += " ";
4275 // Handle nested closure invocation. For example:
4276 //
4277 // void (^myImportedClosure)(void);
4278 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
4279 //
4280 // void (^anotherClosure)(void);
4281 // anotherClosure = ^(void) {
4282 // myImportedClosure(); // import and invoke the closure
4283 // };
4284 //
4285 if (isTopLevelBlockPointerType((*I)->getType())) {
4286 RewriteBlockPointerTypeVariable(S, (*I));
4287 S += " = (";
4288 RewriteBlockPointerType(S, (*I)->getType());
4289 S += ")";
4290 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4291 }
4292 else {
4293 std::string Name = (*I)->getNameAsString();
4294 QualType QT = (*I)->getType();
4295 if (HasLocalVariableExternalStorage(*I))
4296 QT = Context->getPointerType(QT);
4297 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
4298 S += Name + " = __cself->" +
4299 (*I)->getNameAsString() + "; // bound by copy\n";
4300 }
4301 }
4302 std::string RewrittenStr = RewrittenBlockExprs[CE];
4303 const char *cstr = RewrittenStr.c_str();
4304 while (*cstr++ != '{') ;
4305 S += cstr;
4306 S += "\n";
4307 return S;
4308}
4309
4310std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
4311 StringRef funcName,
4312 std::string Tag) {
4313 std::string StructRef = "struct " + Tag;
4314 std::string S = "static void __";
4315
4316 S += funcName;
4317 S += "_block_copy_" + utostr(i);
4318 S += "(" + StructRef;
4319 S += "*dst, " + StructRef;
4320 S += "*src) {";
4321 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
4322 E = ImportedBlockDecls.end(); I != E; ++I) {
4323 ValueDecl *VD = (*I);
4324 S += "_Block_object_assign((void*)&dst->";
4325 S += (*I)->getNameAsString();
4326 S += ", (void*)src->";
4327 S += (*I)->getNameAsString();
4328 if (BlockByRefDeclsPtrSet.count((*I)))
4329 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4330 else if (VD->getType()->isBlockPointerType())
4331 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4332 else
4333 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4334 }
4335 S += "}\n";
4336
4337 S += "\nstatic void __";
4338 S += funcName;
4339 S += "_block_dispose_" + utostr(i);
4340 S += "(" + StructRef;
4341 S += "*src) {";
4342 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
4343 E = ImportedBlockDecls.end(); I != E; ++I) {
4344 ValueDecl *VD = (*I);
4345 S += "_Block_object_dispose((void*)src->";
4346 S += (*I)->getNameAsString();
4347 if (BlockByRefDeclsPtrSet.count((*I)))
4348 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4349 else if (VD->getType()->isBlockPointerType())
4350 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4351 else
4352 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4353 }
4354 S += "}\n";
4355 return S;
4356}
4357
4358std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4359 std::string Desc) {
4360 std::string S = "\nstruct " + Tag;
4361 std::string Constructor = " " + Tag;
4362
4363 S += " {\n struct __block_impl impl;\n";
4364 S += " struct " + Desc;
4365 S += "* Desc;\n";
4366
4367 Constructor += "(void *fp, "; // Invoke function pointer.
4368 Constructor += "struct " + Desc; // Descriptor pointer.
4369 Constructor += " *desc";
4370
4371 if (BlockDeclRefs.size()) {
4372 // Output all "by copy" declarations.
4373 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4374 E = BlockByCopyDecls.end(); I != E; ++I) {
4375 S += " ";
4376 std::string FieldName = (*I)->getNameAsString();
4377 std::string ArgName = "_" + FieldName;
4378 // Handle nested closure invocation. For example:
4379 //
4380 // void (^myImportedBlock)(void);
4381 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
4382 //
4383 // void (^anotherBlock)(void);
4384 // anotherBlock = ^(void) {
4385 // myImportedBlock(); // import and invoke the closure
4386 // };
4387 //
4388 if (isTopLevelBlockPointerType((*I)->getType())) {
4389 S += "struct __block_impl *";
4390 Constructor += ", void *" + ArgName;
4391 } else {
4392 QualType QT = (*I)->getType();
4393 if (HasLocalVariableExternalStorage(*I))
4394 QT = Context->getPointerType(QT);
4395 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
4396 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
4397 Constructor += ", " + ArgName;
4398 }
4399 S += FieldName + ";\n";
4400 }
4401 // Output all "by ref" declarations.
4402 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4403 E = BlockByRefDecls.end(); I != E; ++I) {
4404 S += " ";
4405 std::string FieldName = (*I)->getNameAsString();
4406 std::string ArgName = "_" + FieldName;
4407 {
4408 std::string TypeString;
4409 RewriteByRefString(TypeString, FieldName, (*I));
4410 TypeString += " *";
4411 FieldName = TypeString + FieldName;
4412 ArgName = TypeString + ArgName;
4413 Constructor += ", " + ArgName;
4414 }
4415 S += FieldName + "; // by ref\n";
4416 }
4417 // Finish writing the constructor.
4418 Constructor += ", int flags=0)";
4419 // Initialize all "by copy" arguments.
4420 bool firsTime = true;
4421 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4422 E = BlockByCopyDecls.end(); I != E; ++I) {
4423 std::string Name = (*I)->getNameAsString();
4424 if (firsTime) {
4425 Constructor += " : ";
4426 firsTime = false;
4427 }
4428 else
4429 Constructor += ", ";
4430 if (isTopLevelBlockPointerType((*I)->getType()))
4431 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4432 else
4433 Constructor += Name + "(_" + Name + ")";
4434 }
4435 // Initialize all "by ref" arguments.
4436 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4437 E = BlockByRefDecls.end(); I != E; ++I) {
4438 std::string Name = (*I)->getNameAsString();
4439 if (firsTime) {
4440 Constructor += " : ";
4441 firsTime = false;
4442 }
4443 else
4444 Constructor += ", ";
4445 Constructor += Name + "(_" + Name + "->__forwarding)";
4446 }
4447
4448 Constructor += " {\n";
4449 if (GlobalVarDecl)
4450 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4451 else
4452 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4453 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4454
4455 Constructor += " Desc = desc;\n";
4456 } else {
4457 // Finish writing the constructor.
4458 Constructor += ", int flags=0) {\n";
4459 if (GlobalVarDecl)
4460 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4461 else
4462 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4463 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4464 Constructor += " Desc = desc;\n";
4465 }
4466 Constructor += " ";
4467 Constructor += "}\n";
4468 S += Constructor;
4469 S += "};\n";
4470 return S;
4471}
4472
4473std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag,
4474 std::string ImplTag, int i,
4475 StringRef FunName,
4476 unsigned hasCopy) {
4477 std::string S = "\nstatic struct " + DescTag;
4478
Fariborz Jahanian8b08adb2012-05-03 21:44:12 +00004479 S += " {\n size_t reserved;\n";
4480 S += " size_t Block_size;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004481 if (hasCopy) {
4482 S += " void (*copy)(struct ";
4483 S += ImplTag; S += "*, struct ";
4484 S += ImplTag; S += "*);\n";
4485
4486 S += " void (*dispose)(struct ";
4487 S += ImplTag; S += "*);\n";
4488 }
4489 S += "} ";
4490
4491 S += DescTag + "_DATA = { 0, sizeof(struct ";
4492 S += ImplTag + ")";
4493 if (hasCopy) {
4494 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4495 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
4496 }
4497 S += "};\n";
4498 return S;
4499}
4500
4501void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
4502 StringRef FunName) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004503 bool RewriteSC = (GlobalVarDecl &&
4504 !Blocks.empty() &&
4505 GlobalVarDecl->getStorageClass() == SC_Static &&
4506 GlobalVarDecl->getType().getCVRQualifiers());
4507 if (RewriteSC) {
4508 std::string SC(" void __");
4509 SC += GlobalVarDecl->getNameAsString();
4510 SC += "() {}";
4511 InsertText(FunLocStart, SC);
4512 }
4513
4514 // Insert closures that were part of the function.
4515 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4516 CollectBlockDeclRefInfo(Blocks[i]);
4517 // Need to copy-in the inner copied-in variables not actually used in this
4518 // block.
4519 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
John McCallf4b88a42012-03-10 09:33:50 +00004520 DeclRefExpr *Exp = InnerDeclRefs[count++];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004521 ValueDecl *VD = Exp->getDecl();
4522 BlockDeclRefs.push_back(Exp);
John McCallf4b88a42012-03-10 09:33:50 +00004523 if (!VD->hasAttr<BlocksAttr>()) {
4524 if (!BlockByCopyDeclsPtrSet.count(VD)) {
4525 BlockByCopyDeclsPtrSet.insert(VD);
4526 BlockByCopyDecls.push_back(VD);
4527 }
4528 continue;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004529 }
John McCallf4b88a42012-03-10 09:33:50 +00004530
4531 if (!BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004532 BlockByRefDeclsPtrSet.insert(VD);
4533 BlockByRefDecls.push_back(VD);
4534 }
John McCallf4b88a42012-03-10 09:33:50 +00004535
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004536 // imported objects in the inner blocks not used in the outer
4537 // blocks must be copied/disposed in the outer block as well.
John McCallf4b88a42012-03-10 09:33:50 +00004538 if (VD->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004539 VD->getType()->isBlockPointerType())
4540 ImportedBlockDecls.insert(VD);
4541 }
4542
4543 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4544 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
4545
4546 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
4547
4548 InsertText(FunLocStart, CI);
4549
4550 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
4551
4552 InsertText(FunLocStart, CF);
4553
4554 if (ImportedBlockDecls.size()) {
4555 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
4556 InsertText(FunLocStart, HF);
4557 }
4558 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4559 ImportedBlockDecls.size() > 0);
4560 InsertText(FunLocStart, BD);
4561
4562 BlockDeclRefs.clear();
4563 BlockByRefDecls.clear();
4564 BlockByRefDeclsPtrSet.clear();
4565 BlockByCopyDecls.clear();
4566 BlockByCopyDeclsPtrSet.clear();
4567 ImportedBlockDecls.clear();
4568 }
4569 if (RewriteSC) {
4570 // Must insert any 'const/volatile/static here. Since it has been
4571 // removed as result of rewriting of block literals.
4572 std::string SC;
4573 if (GlobalVarDecl->getStorageClass() == SC_Static)
4574 SC = "static ";
4575 if (GlobalVarDecl->getType().isConstQualified())
4576 SC += "const ";
4577 if (GlobalVarDecl->getType().isVolatileQualified())
4578 SC += "volatile ";
4579 if (GlobalVarDecl->getType().isRestrictQualified())
4580 SC += "restrict ";
4581 InsertText(FunLocStart, SC);
4582 }
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004583 if (GlobalConstructionExp) {
4584 // extra fancy dance for global literal expression.
4585
4586 // Always the latest block expression on the block stack.
4587 std::string Tag = "__";
4588 Tag += FunName;
4589 Tag += "_block_impl_";
4590 Tag += utostr(Blocks.size()-1);
4591 std::string globalBuf = "static ";
4592 globalBuf += Tag; globalBuf += " ";
4593 std::string SStr;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004594
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004595 llvm::raw_string_ostream constructorExprBuf(SStr);
Richard Smithd1420c62012-08-16 03:56:14 +00004596 GlobalConstructionExp->printPretty(constructorExprBuf, 0,
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004597 PrintingPolicy(LangOpts));
4598 globalBuf += constructorExprBuf.str();
4599 globalBuf += ";\n";
4600 InsertText(FunLocStart, globalBuf);
4601 GlobalConstructionExp = 0;
4602 }
4603
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004604 Blocks.clear();
4605 InnerDeclRefsCount.clear();
4606 InnerDeclRefs.clear();
4607 RewrittenBlockExprs.clear();
4608}
4609
4610void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
Fariborz Jahanian04189532012-04-25 17:56:48 +00004611 SourceLocation FunLocStart =
4612 (!Blocks.empty()) ? getFunctionSourceLocation(*this, FD)
4613 : FD->getTypeSpecStartLoc();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004614 StringRef FuncName = FD->getName();
4615
4616 SynthesizeBlockLiterals(FunLocStart, FuncName);
4617}
4618
4619static void BuildUniqueMethodName(std::string &Name,
4620 ObjCMethodDecl *MD) {
4621 ObjCInterfaceDecl *IFace = MD->getClassInterface();
4622 Name = IFace->getName();
4623 Name += "__" + MD->getSelector().getAsString();
4624 // Convert colons to underscores.
4625 std::string::size_type loc = 0;
4626 while ((loc = Name.find(":", loc)) != std::string::npos)
4627 Name.replace(loc, 1, "_");
4628}
4629
4630void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
4631 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4632 //SourceLocation FunLocStart = MD->getLocStart();
4633 SourceLocation FunLocStart = MD->getLocStart();
4634 std::string FuncName;
4635 BuildUniqueMethodName(FuncName, MD);
4636 SynthesizeBlockLiterals(FunLocStart, FuncName);
4637}
4638
4639void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
4640 for (Stmt::child_range CI = S->children(); CI; ++CI)
4641 if (*CI) {
4642 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4643 GetBlockDeclRefExprs(CBE->getBody());
4644 else
4645 GetBlockDeclRefExprs(*CI);
4646 }
4647 // Handle specific things.
Fariborz Jahanian0e976812012-04-16 23:00:57 +00004648 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4649 if (DRE->refersToEnclosingLocal()) {
4650 // FIXME: Handle enums.
4651 if (!isa<FunctionDecl>(DRE->getDecl()))
4652 BlockDeclRefs.push_back(DRE);
4653 if (HasLocalVariableExternalStorage(DRE->getDecl()))
4654 BlockDeclRefs.push_back(DRE);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004655 }
Fariborz Jahanian0e976812012-04-16 23:00:57 +00004656 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004657
4658 return;
4659}
4660
4661void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
John McCallf4b88a42012-03-10 09:33:50 +00004662 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004663 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
4664 for (Stmt::child_range CI = S->children(); CI; ++CI)
4665 if (*CI) {
4666 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
4667 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
4668 GetInnerBlockDeclRefExprs(CBE->getBody(),
4669 InnerBlockDeclRefs,
4670 InnerContexts);
4671 }
4672 else
4673 GetInnerBlockDeclRefExprs(*CI,
4674 InnerBlockDeclRefs,
4675 InnerContexts);
4676
4677 }
4678 // Handle specific things.
John McCallf4b88a42012-03-10 09:33:50 +00004679 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4680 if (DRE->refersToEnclosingLocal()) {
4681 if (!isa<FunctionDecl>(DRE->getDecl()) &&
4682 !InnerContexts.count(DRE->getDecl()->getDeclContext()))
4683 InnerBlockDeclRefs.push_back(DRE);
4684 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
4685 if (Var->isFunctionOrMethodVarDecl())
4686 ImportedLocalExternalDecls.insert(Var);
4687 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004688 }
4689
4690 return;
4691}
4692
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004693/// convertObjCTypeToCStyleType - This routine converts such objc types
4694/// as qualified objects, and blocks to their closest c/c++ types that
4695/// it can. It returns true if input type was modified.
4696bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
4697 QualType oldT = T;
4698 convertBlockPointerToFunctionPointer(T);
4699 if (T->isFunctionPointerType()) {
4700 QualType PointeeTy;
4701 if (const PointerType* PT = T->getAs<PointerType>()) {
4702 PointeeTy = PT->getPointeeType();
4703 if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
4704 T = convertFunctionTypeOfBlocks(FT);
4705 T = Context->getPointerType(T);
4706 }
4707 }
4708 }
4709
4710 convertToUnqualifiedObjCType(T);
4711 return T != oldT;
4712}
4713
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004714/// convertFunctionTypeOfBlocks - This routine converts a function type
4715/// whose result type may be a block pointer or whose argument type(s)
4716/// might be block pointers to an equivalent function type replacing
4717/// all block pointers to function pointers.
4718QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4719 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4720 // FTP will be null for closures that don't take arguments.
4721 // Generate a funky cast.
4722 SmallVector<QualType, 8> ArgTypes;
4723 QualType Res = FT->getResultType();
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004724 bool modified = convertObjCTypeToCStyleType(Res);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004725
4726 if (FTP) {
4727 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4728 E = FTP->arg_type_end(); I && (I != E); ++I) {
4729 QualType t = *I;
4730 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004731 if (convertObjCTypeToCStyleType(t))
4732 modified = true;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004733 ArgTypes.push_back(t);
4734 }
4735 }
4736 QualType FuncType;
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004737 if (modified)
Jordan Rosebea522f2013-03-08 21:51:21 +00004738 FuncType = getSimpleFunctionType(Res, ArgTypes);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004739 else FuncType = QualType(FT, 0);
4740 return FuncType;
4741}
4742
4743Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
4744 // Navigate to relevant type information.
4745 const BlockPointerType *CPT = 0;
4746
4747 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
4748 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004749 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
4750 CPT = MExpr->getType()->getAs<BlockPointerType>();
4751 }
4752 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4753 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4754 }
4755 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4756 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4757 else if (const ConditionalOperator *CEXPR =
4758 dyn_cast<ConditionalOperator>(BlockExp)) {
4759 Expr *LHSExp = CEXPR->getLHS();
4760 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4761 Expr *RHSExp = CEXPR->getRHS();
4762 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4763 Expr *CONDExp = CEXPR->getCond();
4764 ConditionalOperator *CondExpr =
4765 new (Context) ConditionalOperator(CONDExp,
4766 SourceLocation(), cast<Expr>(LHSStmt),
4767 SourceLocation(), cast<Expr>(RHSStmt),
4768 Exp->getType(), VK_RValue, OK_Ordinary);
4769 return CondExpr;
4770 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4771 CPT = IRE->getType()->getAs<BlockPointerType>();
4772 } else if (const PseudoObjectExpr *POE
4773 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
4774 CPT = POE->getType()->castAs<BlockPointerType>();
4775 } else {
4776 assert(1 && "RewriteBlockClass: Bad type");
4777 }
4778 assert(CPT && "RewriteBlockClass: Bad type");
4779 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
4780 assert(FT && "RewriteBlockClass: Bad type");
4781 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4782 // FTP will be null for closures that don't take arguments.
4783
4784 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4785 SourceLocation(), SourceLocation(),
4786 &Context->Idents.get("__block_impl"));
4787 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
4788
4789 // Generate a funky cast.
4790 SmallVector<QualType, 8> ArgTypes;
4791
4792 // Push the block argument type.
4793 ArgTypes.push_back(PtrBlock);
4794 if (FTP) {
4795 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4796 E = FTP->arg_type_end(); I && (I != E); ++I) {
4797 QualType t = *I;
4798 // Make sure we convert "t (^)(...)" to "t (*)(...)".
4799 if (!convertBlockPointerToFunctionPointer(t))
4800 convertToUnqualifiedObjCType(t);
4801 ArgTypes.push_back(t);
4802 }
4803 }
4804 // Now do the pointer to function cast.
Jordan Rosebea522f2013-03-08 21:51:21 +00004805 QualType PtrToFuncCastType = getSimpleFunctionType(Exp->getType(), ArgTypes);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004806
4807 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
4808
4809 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4810 CK_BitCast,
4811 const_cast<Expr*>(BlockExp));
4812 // Don't forget the parens to enforce the proper binding.
4813 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4814 BlkCast);
4815 //PE->dump();
4816
4817 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4818 SourceLocation(),
4819 &Context->Idents.get("FuncPtr"),
4820 Context->VoidPtrTy, 0,
4821 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00004822 ICIS_NoInit);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004823 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4824 FD->getType(), VK_LValue,
4825 OK_Ordinary);
4826
4827
4828 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4829 CK_BitCast, ME);
4830 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
4831
4832 SmallVector<Expr*, 8> BlkExprs;
4833 // Add the implicit argument.
4834 BlkExprs.push_back(BlkCast);
4835 // Add the user arguments.
4836 for (CallExpr::arg_iterator I = Exp->arg_begin(),
4837 E = Exp->arg_end(); I != E; ++I) {
4838 BlkExprs.push_back(*I);
4839 }
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004840 CallExpr *CE = new (Context) CallExpr(*Context, PE, BlkExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004841 Exp->getType(), VK_RValue,
4842 SourceLocation());
4843 return CE;
4844}
4845
4846// We need to return the rewritten expression to handle cases where the
John McCallf4b88a42012-03-10 09:33:50 +00004847// DeclRefExpr is embedded in another expression being rewritten.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004848// For example:
4849//
4850// int main() {
4851// __block Foo *f;
4852// __block int i;
4853//
4854// void (^myblock)() = ^() {
John McCallf4b88a42012-03-10 09:33:50 +00004855// [f test]; // f is a DeclRefExpr embedded in a message (which is being rewritten).
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004856// i = 77;
4857// };
4858//}
John McCallf4b88a42012-03-10 09:33:50 +00004859Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004860 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
4861 // for each DeclRefExp where BYREFVAR is name of the variable.
John McCallf4b88a42012-03-10 09:33:50 +00004862 ValueDecl *VD = DeclRefExp->getDecl();
4863 bool isArrow = DeclRefExp->refersToEnclosingLocal();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004864
4865 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4866 SourceLocation(),
4867 &Context->Idents.get("__forwarding"),
4868 Context->VoidPtrTy, 0,
4869 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00004870 ICIS_NoInit);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004871 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4872 FD, SourceLocation(),
4873 FD->getType(), VK_LValue,
4874 OK_Ordinary);
4875
4876 StringRef Name = VD->getName();
4877 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
4878 &Context->Idents.get(Name),
4879 Context->VoidPtrTy, 0,
4880 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00004881 ICIS_NoInit);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004882 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
4883 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
4884
4885
4886
4887 // Need parens to enforce precedence.
4888 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
4889 DeclRefExp->getExprLoc(),
4890 ME);
4891 ReplaceStmt(DeclRefExp, PE);
4892 return PE;
4893}
4894
4895// Rewrites the imported local variable V with external storage
4896// (static, extern, etc.) as *V
4897//
4898Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4899 ValueDecl *VD = DRE->getDecl();
4900 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4901 if (!ImportedLocalExternalDecls.count(Var))
4902 return DRE;
4903 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4904 VK_LValue, OK_Ordinary,
4905 DRE->getLocation());
4906 // Need parens to enforce precedence.
4907 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4908 Exp);
4909 ReplaceStmt(DRE, PE);
4910 return PE;
4911}
4912
4913void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4914 SourceLocation LocStart = CE->getLParenLoc();
4915 SourceLocation LocEnd = CE->getRParenLoc();
4916
4917 // Need to avoid trying to rewrite synthesized casts.
4918 if (LocStart.isInvalid())
4919 return;
4920 // Need to avoid trying to rewrite casts contained in macros.
4921 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4922 return;
4923
4924 const char *startBuf = SM->getCharacterData(LocStart);
4925 const char *endBuf = SM->getCharacterData(LocEnd);
4926 QualType QT = CE->getType();
4927 const Type* TypePtr = QT->getAs<Type>();
4928 if (isa<TypeOfExprType>(TypePtr)) {
4929 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4930 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4931 std::string TypeAsString = "(";
4932 RewriteBlockPointerType(TypeAsString, QT);
4933 TypeAsString += ")";
4934 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
4935 return;
4936 }
4937 // advance the location to startArgList.
4938 const char *argPtr = startBuf;
4939
4940 while (*argPtr++ && (argPtr < endBuf)) {
4941 switch (*argPtr) {
4942 case '^':
4943 // Replace the '^' with '*'.
4944 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
4945 ReplaceText(LocStart, 1, "*");
4946 break;
4947 }
4948 }
4949 return;
4950}
4951
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00004952void RewriteModernObjC::RewriteImplicitCastObjCExpr(CastExpr *IC) {
4953 CastKind CastKind = IC->getCastKind();
Fariborz Jahanian43aa1c32012-04-16 22:14:01 +00004954 if (CastKind != CK_BlockPointerToObjCPointerCast &&
4955 CastKind != CK_AnyPointerToBlockPointerCast)
4956 return;
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00004957
Fariborz Jahanian43aa1c32012-04-16 22:14:01 +00004958 QualType QT = IC->getType();
4959 (void)convertBlockPointerToFunctionPointer(QT);
4960 std::string TypeString(QT.getAsString(Context->getPrintingPolicy()));
4961 std::string Str = "(";
4962 Str += TypeString;
4963 Str += ")";
4964 InsertText(IC->getSubExpr()->getLocStart(), &Str[0], Str.size());
4965
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00004966 return;
4967}
4968
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004969void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4970 SourceLocation DeclLoc = FD->getLocation();
4971 unsigned parenCount = 0;
4972
4973 // We have 1 or more arguments that have closure pointers.
4974 const char *startBuf = SM->getCharacterData(DeclLoc);
4975 const char *startArgList = strchr(startBuf, '(');
4976
4977 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
4978
4979 parenCount++;
4980 // advance the location to startArgList.
4981 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
4982 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
4983
4984 const char *argPtr = startArgList;
4985
4986 while (*argPtr++ && parenCount) {
4987 switch (*argPtr) {
4988 case '^':
4989 // Replace the '^' with '*'.
4990 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
4991 ReplaceText(DeclLoc, 1, "*");
4992 break;
4993 case '(':
4994 parenCount++;
4995 break;
4996 case ')':
4997 parenCount--;
4998 break;
4999 }
5000 }
5001 return;
5002}
5003
5004bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
5005 const FunctionProtoType *FTP;
5006 const PointerType *PT = QT->getAs<PointerType>();
5007 if (PT) {
5008 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
5009 } else {
5010 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
5011 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
5012 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
5013 }
5014 if (FTP) {
5015 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
5016 E = FTP->arg_type_end(); I != E; ++I)
5017 if (isTopLevelBlockPointerType(*I))
5018 return true;
5019 }
5020 return false;
5021}
5022
5023bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
5024 const FunctionProtoType *FTP;
5025 const PointerType *PT = QT->getAs<PointerType>();
5026 if (PT) {
5027 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
5028 } else {
5029 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
5030 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
5031 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
5032 }
5033 if (FTP) {
5034 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
5035 E = FTP->arg_type_end(); I != E; ++I) {
5036 if ((*I)->isObjCQualifiedIdType())
5037 return true;
5038 if ((*I)->isObjCObjectPointerType() &&
5039 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
5040 return true;
5041 }
5042
5043 }
5044 return false;
5045}
5046
5047void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
5048 const char *&RParen) {
5049 const char *argPtr = strchr(Name, '(');
5050 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
5051
5052 LParen = argPtr; // output the start.
5053 argPtr++; // skip past the left paren.
5054 unsigned parenCount = 1;
5055
5056 while (*argPtr && parenCount) {
5057 switch (*argPtr) {
5058 case '(': parenCount++; break;
5059 case ')': parenCount--; break;
5060 default: break;
5061 }
5062 if (parenCount) argPtr++;
5063 }
5064 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
5065 RParen = argPtr; // output the end
5066}
5067
5068void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
5069 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
5070 RewriteBlockPointerFunctionArgs(FD);
5071 return;
5072 }
5073 // Handle Variables and Typedefs.
5074 SourceLocation DeclLoc = ND->getLocation();
5075 QualType DeclT;
5076 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
5077 DeclT = VD->getType();
5078 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
5079 DeclT = TDD->getUnderlyingType();
5080 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
5081 DeclT = FD->getType();
5082 else
5083 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
5084
5085 const char *startBuf = SM->getCharacterData(DeclLoc);
5086 const char *endBuf = startBuf;
5087 // scan backward (from the decl location) for the end of the previous decl.
5088 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
5089 startBuf--;
5090 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
5091 std::string buf;
5092 unsigned OrigLength=0;
5093 // *startBuf != '^' if we are dealing with a pointer to function that
5094 // may take block argument types (which will be handled below).
5095 if (*startBuf == '^') {
5096 // Replace the '^' with '*', computing a negative offset.
5097 buf = '*';
5098 startBuf++;
5099 OrigLength++;
5100 }
5101 while (*startBuf != ')') {
5102 buf += *startBuf;
5103 startBuf++;
5104 OrigLength++;
5105 }
5106 buf += ')';
5107 OrigLength++;
5108
5109 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
5110 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
5111 // Replace the '^' with '*' for arguments.
5112 // Replace id<P> with id/*<>*/
5113 DeclLoc = ND->getLocation();
5114 startBuf = SM->getCharacterData(DeclLoc);
5115 const char *argListBegin, *argListEnd;
5116 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
5117 while (argListBegin < argListEnd) {
5118 if (*argListBegin == '^')
5119 buf += '*';
5120 else if (*argListBegin == '<') {
5121 buf += "/*";
5122 buf += *argListBegin++;
Dmitri Gribenko1ad23d62012-09-10 21:20:09 +00005123 OrigLength++;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005124 while (*argListBegin != '>') {
5125 buf += *argListBegin++;
5126 OrigLength++;
5127 }
5128 buf += *argListBegin;
5129 buf += "*/";
5130 }
5131 else
5132 buf += *argListBegin;
5133 argListBegin++;
5134 OrigLength++;
5135 }
5136 buf += ')';
5137 OrigLength++;
5138 }
5139 ReplaceText(Start, OrigLength, buf);
5140
5141 return;
5142}
5143
5144
5145/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
5146/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
5147/// struct Block_byref_id_object *src) {
5148/// _Block_object_assign (&_dest->object, _src->object,
5149/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5150/// [|BLOCK_FIELD_IS_WEAK]) // object
5151/// _Block_object_assign(&_dest->object, _src->object,
5152/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5153/// [|BLOCK_FIELD_IS_WEAK]) // block
5154/// }
5155/// And:
5156/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
5157/// _Block_object_dispose(_src->object,
5158/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5159/// [|BLOCK_FIELD_IS_WEAK]) // object
5160/// _Block_object_dispose(_src->object,
5161/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5162/// [|BLOCK_FIELD_IS_WEAK]) // block
5163/// }
5164
5165std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
5166 int flag) {
5167 std::string S;
5168 if (CopyDestroyCache.count(flag))
5169 return S;
5170 CopyDestroyCache.insert(flag);
5171 S = "static void __Block_byref_id_object_copy_";
5172 S += utostr(flag);
5173 S += "(void *dst, void *src) {\n";
5174
5175 // offset into the object pointer is computed as:
5176 // void * + void* + int + int + void* + void *
5177 unsigned IntSize =
5178 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5179 unsigned VoidPtrSize =
5180 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
5181
5182 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
5183 S += " _Block_object_assign((char*)dst + ";
5184 S += utostr(offset);
5185 S += ", *(void * *) ((char*)src + ";
5186 S += utostr(offset);
5187 S += "), ";
5188 S += utostr(flag);
5189 S += ");\n}\n";
5190
5191 S += "static void __Block_byref_id_object_dispose_";
5192 S += utostr(flag);
5193 S += "(void *src) {\n";
5194 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
5195 S += utostr(offset);
5196 S += "), ";
5197 S += utostr(flag);
5198 S += ");\n}\n";
5199 return S;
5200}
5201
5202/// RewriteByRefVar - For each __block typex ND variable this routine transforms
5203/// the declaration into:
5204/// struct __Block_byref_ND {
5205/// void *__isa; // NULL for everything except __weak pointers
5206/// struct __Block_byref_ND *__forwarding;
5207/// int32_t __flags;
5208/// int32_t __size;
5209/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
5210/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
5211/// typex ND;
5212/// };
5213///
5214/// It then replaces declaration of ND variable with:
5215/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
5216/// __size=sizeof(struct __Block_byref_ND),
5217/// ND=initializer-if-any};
5218///
5219///
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00005220void RewriteModernObjC::RewriteByRefVar(VarDecl *ND, bool firstDecl,
5221 bool lastDecl) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005222 int flag = 0;
5223 int isa = 0;
5224 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
5225 if (DeclLoc.isInvalid())
5226 // If type location is missing, it is because of missing type (a warning).
5227 // Use variable's location which is good for this case.
5228 DeclLoc = ND->getLocation();
5229 const char *startBuf = SM->getCharacterData(DeclLoc);
5230 SourceLocation X = ND->getLocEnd();
5231 X = SM->getExpansionLoc(X);
5232 const char *endBuf = SM->getCharacterData(X);
5233 std::string Name(ND->getNameAsString());
5234 std::string ByrefType;
5235 RewriteByRefString(ByrefType, Name, ND, true);
5236 ByrefType += " {\n";
5237 ByrefType += " void *__isa;\n";
5238 RewriteByRefString(ByrefType, Name, ND);
5239 ByrefType += " *__forwarding;\n";
5240 ByrefType += " int __flags;\n";
5241 ByrefType += " int __size;\n";
5242 // Add void *__Block_byref_id_object_copy;
5243 // void *__Block_byref_id_object_dispose; if needed.
5244 QualType Ty = ND->getType();
Fariborz Jahanianb15c8982012-11-28 23:12:17 +00005245 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty, ND);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005246 if (HasCopyAndDispose) {
5247 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
5248 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
5249 }
5250
5251 QualType T = Ty;
5252 (void)convertBlockPointerToFunctionPointer(T);
5253 T.getAsStringInternal(Name, Context->getPrintingPolicy());
5254
5255 ByrefType += " " + Name + ";\n";
5256 ByrefType += "};\n";
5257 // Insert this type in global scope. It is needed by helper function.
5258 SourceLocation FunLocStart;
5259 if (CurFunctionDef)
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00005260 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005261 else {
5262 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
5263 FunLocStart = CurMethodDef->getLocStart();
5264 }
5265 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian8247c4e2012-04-24 16:45:27 +00005266
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005267 if (Ty.isObjCGCWeak()) {
5268 flag |= BLOCK_FIELD_IS_WEAK;
5269 isa = 1;
5270 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005271 if (HasCopyAndDispose) {
5272 flag = BLOCK_BYREF_CALLER;
5273 QualType Ty = ND->getType();
5274 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
5275 if (Ty->isBlockPointerType())
5276 flag |= BLOCK_FIELD_IS_BLOCK;
5277 else
5278 flag |= BLOCK_FIELD_IS_OBJECT;
5279 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
5280 if (!HF.empty())
Fariborz Jahanian31c4a4b2013-02-07 22:50:40 +00005281 Preamble += HF;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005282 }
5283
5284 // struct __Block_byref_ND ND =
5285 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
5286 // initializer-if-any};
5287 bool hasInit = (ND->getInit() != 0);
Fariborz Jahanian104dbf92012-04-11 23:57:12 +00005288 // FIXME. rewriter does not support __block c++ objects which
5289 // require construction.
Fariborz Jahanian65a7c682012-04-26 23:20:25 +00005290 if (hasInit)
5291 if (CXXConstructExpr *CExp = dyn_cast<CXXConstructExpr>(ND->getInit())) {
5292 CXXConstructorDecl *CXXDecl = CExp->getConstructor();
5293 if (CXXDecl && CXXDecl->isDefaultConstructor())
5294 hasInit = false;
5295 }
5296
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005297 unsigned flags = 0;
5298 if (HasCopyAndDispose)
5299 flags |= BLOCK_HAS_COPY_DISPOSE;
5300 Name = ND->getNameAsString();
5301 ByrefType.clear();
5302 RewriteByRefString(ByrefType, Name, ND);
5303 std::string ForwardingCastType("(");
5304 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian8247c4e2012-04-24 16:45:27 +00005305 ByrefType += " " + Name + " = {(void*)";
5306 ByrefType += utostr(isa);
5307 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
5308 ByrefType += utostr(flags);
5309 ByrefType += ", ";
5310 ByrefType += "sizeof(";
5311 RewriteByRefString(ByrefType, Name, ND);
5312 ByrefType += ")";
5313 if (HasCopyAndDispose) {
5314 ByrefType += ", __Block_byref_id_object_copy_";
5315 ByrefType += utostr(flag);
5316 ByrefType += ", __Block_byref_id_object_dispose_";
5317 ByrefType += utostr(flag);
5318 }
5319
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00005320 if (!firstDecl) {
5321 // In multiple __block declarations, and for all but 1st declaration,
5322 // find location of the separating comma. This would be start location
5323 // where new text is to be inserted.
5324 DeclLoc = ND->getLocation();
5325 const char *startDeclBuf = SM->getCharacterData(DeclLoc);
5326 const char *commaBuf = startDeclBuf;
5327 while (*commaBuf != ',')
5328 commaBuf--;
5329 assert((*commaBuf == ',') && "RewriteByRefVar: can't find ','");
5330 DeclLoc = DeclLoc.getLocWithOffset(commaBuf - startDeclBuf);
5331 startBuf = commaBuf;
5332 }
5333
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005334 if (!hasInit) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005335 ByrefType += "};\n";
5336 unsigned nameSize = Name.size();
5337 // for block or function pointer declaration. Name is aleady
5338 // part of the declaration.
5339 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
5340 nameSize = 1;
5341 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
5342 }
5343 else {
Fariborz Jahanian8247c4e2012-04-24 16:45:27 +00005344 ByrefType += ", ";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005345 SourceLocation startLoc;
5346 Expr *E = ND->getInit();
5347 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5348 startLoc = ECE->getLParenLoc();
5349 else
5350 startLoc = E->getLocStart();
5351 startLoc = SM->getExpansionLoc(startLoc);
5352 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005353 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005354
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00005355 const char separator = lastDecl ? ';' : ',';
5356 const char *startInitializerBuf = SM->getCharacterData(startLoc);
5357 const char *separatorBuf = strchr(startInitializerBuf, separator);
5358 assert((*separatorBuf == separator) &&
5359 "RewriteByRefVar: can't find ';' or ','");
5360 SourceLocation separatorLoc =
5361 startLoc.getLocWithOffset(separatorBuf-startInitializerBuf);
5362
5363 InsertText(separatorLoc, lastDecl ? "}" : "};\n");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005364 }
5365 return;
5366}
5367
5368void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
5369 // Add initializers for any closure decl refs.
5370 GetBlockDeclRefExprs(Exp->getBody());
5371 if (BlockDeclRefs.size()) {
5372 // Unique all "by copy" declarations.
5373 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00005374 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005375 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5376 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5377 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5378 }
5379 }
5380 // Unique all "by ref" declarations.
5381 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00005382 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005383 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5384 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5385 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5386 }
5387 }
5388 // Find any imported blocks...they will need special attention.
5389 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00005390 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005391 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5392 BlockDeclRefs[i]->getType()->isBlockPointerType())
5393 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
5394 }
5395}
5396
5397FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) {
5398 IdentifierInfo *ID = &Context->Idents.get(name);
5399 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
5400 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
5401 SourceLocation(), ID, FType, 0, SC_Extern,
Rafael Espindola8f187f62013-04-03 15:50:00 +00005402 false, false);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005403}
5404
5405Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp,
John McCallf4b88a42012-03-10 09:33:50 +00005406 const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs) {
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +00005407
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005408 const BlockDecl *block = Exp->getBlockDecl();
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +00005409
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005410 Blocks.push_back(Exp);
5411
5412 CollectBlockDeclRefInfo(Exp);
5413
5414 // Add inner imported variables now used in current block.
5415 int countOfInnerDecls = 0;
5416 if (!InnerBlockDeclRefs.empty()) {
5417 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
John McCallf4b88a42012-03-10 09:33:50 +00005418 DeclRefExpr *Exp = InnerBlockDeclRefs[i];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005419 ValueDecl *VD = Exp->getDecl();
John McCallf4b88a42012-03-10 09:33:50 +00005420 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005421 // We need to save the copied-in variables in nested
5422 // blocks because it is needed at the end for some of the API generations.
5423 // See SynthesizeBlockLiterals routine.
5424 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5425 BlockDeclRefs.push_back(Exp);
5426 BlockByCopyDeclsPtrSet.insert(VD);
5427 BlockByCopyDecls.push_back(VD);
5428 }
John McCallf4b88a42012-03-10 09:33:50 +00005429 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005430 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5431 BlockDeclRefs.push_back(Exp);
5432 BlockByRefDeclsPtrSet.insert(VD);
5433 BlockByRefDecls.push_back(VD);
5434 }
5435 }
5436 // Find any imported blocks...they will need special attention.
5437 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00005438 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005439 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5440 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5441 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
5442 }
5443 InnerDeclRefsCount.push_back(countOfInnerDecls);
5444
5445 std::string FuncName;
5446
5447 if (CurFunctionDef)
5448 FuncName = CurFunctionDef->getNameAsString();
5449 else if (CurMethodDef)
5450 BuildUniqueMethodName(FuncName, CurMethodDef);
5451 else if (GlobalVarDecl)
5452 FuncName = std::string(GlobalVarDecl->getNameAsString());
5453
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00005454 bool GlobalBlockExpr =
5455 block->getDeclContext()->getRedeclContext()->isFileContext();
5456
5457 if (GlobalBlockExpr && !GlobalVarDecl) {
5458 Diags.Report(block->getLocation(), GlobalBlockRewriteFailedDiag);
5459 GlobalBlockExpr = false;
5460 }
5461
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005462 std::string BlockNumber = utostr(Blocks.size()-1);
5463
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005464 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
5465
5466 // Get a pointer to the function type so we can cast appropriately.
5467 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5468 QualType FType = Context->getPointerType(BFT);
5469
5470 FunctionDecl *FD;
5471 Expr *NewRep;
5472
5473 // Simulate a contructor call...
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00005474 std::string Tag;
5475
5476 if (GlobalBlockExpr)
5477 Tag = "__global_";
5478 else
5479 Tag = "__";
5480 Tag += FuncName + "_block_impl_" + BlockNumber;
5481
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005482 FD = SynthBlockInitFunctionDecl(Tag);
John McCallf4b88a42012-03-10 09:33:50 +00005483 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005484 SourceLocation());
5485
5486 SmallVector<Expr*, 4> InitExprs;
5487
5488 // Initialize the block function.
5489 FD = SynthBlockInitFunctionDecl(Func);
John McCallf4b88a42012-03-10 09:33:50 +00005490 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5491 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005492 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5493 CK_BitCast, Arg);
5494 InitExprs.push_back(castExpr);
5495
5496 // Initialize the block descriptor.
5497 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
5498
5499 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
5500 SourceLocation(), SourceLocation(),
5501 &Context->Idents.get(DescData.c_str()),
5502 Context->VoidPtrTy, 0,
Rafael Espindola8f187f62013-04-03 15:50:00 +00005503 SC_Static);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005504 UnaryOperator *DescRefExpr =
John McCallf4b88a42012-03-10 09:33:50 +00005505 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005506 Context->VoidPtrTy,
5507 VK_LValue,
5508 SourceLocation()),
5509 UO_AddrOf,
5510 Context->getPointerType(Context->VoidPtrTy),
5511 VK_RValue, OK_Ordinary,
5512 SourceLocation());
5513 InitExprs.push_back(DescRefExpr);
5514
5515 // Add initializers for any closure decl refs.
5516 if (BlockDeclRefs.size()) {
5517 Expr *Exp;
5518 // Output all "by copy" declarations.
5519 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
5520 E = BlockByCopyDecls.end(); I != E; ++I) {
5521 if (isObjCType((*I)->getType())) {
5522 // FIXME: Conform to ABI ([[obj retain] autorelease]).
5523 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005524 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5525 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005526 if (HasLocalVariableExternalStorage(*I)) {
5527 QualType QT = (*I)->getType();
5528 QT = Context->getPointerType(QT);
5529 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5530 OK_Ordinary, SourceLocation());
5531 }
5532 } else if (isTopLevelBlockPointerType((*I)->getType())) {
5533 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005534 Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5535 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005536 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5537 CK_BitCast, Arg);
5538 } else {
5539 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005540 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5541 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005542 if (HasLocalVariableExternalStorage(*I)) {
5543 QualType QT = (*I)->getType();
5544 QT = Context->getPointerType(QT);
5545 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5546 OK_Ordinary, SourceLocation());
5547 }
5548
5549 }
5550 InitExprs.push_back(Exp);
5551 }
5552 // Output all "by ref" declarations.
5553 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
5554 E = BlockByRefDecls.end(); I != E; ++I) {
5555 ValueDecl *ND = (*I);
5556 std::string Name(ND->getNameAsString());
5557 std::string RecName;
5558 RewriteByRefString(RecName, Name, ND, true);
5559 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5560 + sizeof("struct"));
5561 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5562 SourceLocation(), SourceLocation(),
5563 II);
5564 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5565 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5566
5567 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005568 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005569 SourceLocation());
5570 bool isNestedCapturedVar = false;
5571 if (block)
5572 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
5573 ce = block->capture_end(); ci != ce; ++ci) {
5574 const VarDecl *variable = ci->getVariable();
5575 if (variable == ND && ci->isNested()) {
5576 assert (ci->isByRef() &&
5577 "SynthBlockInitExpr - captured block variable is not byref");
5578 isNestedCapturedVar = true;
5579 break;
5580 }
5581 }
5582 // captured nested byref variable has its address passed. Do not take
5583 // its address again.
5584 if (!isNestedCapturedVar)
5585 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
5586 Context->getPointerType(Exp->getType()),
5587 VK_RValue, OK_Ordinary, SourceLocation());
5588 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
5589 InitExprs.push_back(Exp);
5590 }
5591 }
5592 if (ImportedBlockDecls.size()) {
5593 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5594 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
5595 unsigned IntSize =
5596 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5597 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5598 Context->IntTy, SourceLocation());
5599 InitExprs.push_back(FlagExp);
5600 }
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00005601 NewRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005602 FType, VK_LValue, SourceLocation());
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00005603
5604 if (GlobalBlockExpr) {
5605 assert (GlobalConstructionExp == 0 &&
5606 "SynthBlockInitExpr - GlobalConstructionExp must be null");
5607 GlobalConstructionExp = NewRep;
5608 NewRep = DRE;
5609 }
5610
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005611 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
5612 Context->getPointerType(NewRep->getType()),
5613 VK_RValue, OK_Ordinary, SourceLocation());
5614 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
5615 NewRep);
5616 BlockDeclRefs.clear();
5617 BlockByRefDecls.clear();
5618 BlockByRefDeclsPtrSet.clear();
5619 BlockByCopyDecls.clear();
5620 BlockByCopyDeclsPtrSet.clear();
5621 ImportedBlockDecls.clear();
5622 return NewRep;
5623}
5624
5625bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
5626 if (const ObjCForCollectionStmt * CS =
5627 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
5628 return CS->getElement() == DS;
5629 return false;
5630}
5631
5632//===----------------------------------------------------------------------===//
5633// Function Body / Expression rewriting
5634//===----------------------------------------------------------------------===//
5635
5636Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
5637 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5638 isa<DoStmt>(S) || isa<ForStmt>(S))
5639 Stmts.push_back(S);
5640 else if (isa<ObjCForCollectionStmt>(S)) {
5641 Stmts.push_back(S);
5642 ObjCBcLabelNo.push_back(++BcLabelCount);
5643 }
5644
5645 // Pseudo-object operations and ivar references need special
5646 // treatment because we're going to recursively rewrite them.
5647 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
5648 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
5649 return RewritePropertyOrImplicitSetter(PseudoOp);
5650 } else {
5651 return RewritePropertyOrImplicitGetter(PseudoOp);
5652 }
5653 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5654 return RewriteObjCIvarRefExpr(IvarRefExpr);
5655 }
Fariborz Jahanian9ffd1ae2013-02-08 18:57:50 +00005656 else if (isa<OpaqueValueExpr>(S))
5657 S = cast<OpaqueValueExpr>(S)->getSourceExpr();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005658
5659 SourceRange OrigStmtRange = S->getSourceRange();
5660
5661 // Perform a bottom up rewrite of all children.
5662 for (Stmt::child_range CI = S->children(); CI; ++CI)
5663 if (*CI) {
5664 Stmt *childStmt = (*CI);
5665 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
5666 if (newStmt) {
5667 *CI = newStmt;
5668 }
5669 }
5670
5671 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
John McCallf4b88a42012-03-10 09:33:50 +00005672 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005673 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5674 InnerContexts.insert(BE->getBlockDecl());
5675 ImportedLocalExternalDecls.clear();
5676 GetInnerBlockDeclRefExprs(BE->getBody(),
5677 InnerBlockDeclRefs, InnerContexts);
5678 // Rewrite the block body in place.
5679 Stmt *SaveCurrentBody = CurrentBody;
5680 CurrentBody = BE->getBody();
5681 PropParentMap = 0;
5682 // block literal on rhs of a property-dot-sytax assignment
5683 // must be replaced by its synthesize ast so getRewrittenText
5684 // works as expected. In this case, what actually ends up on RHS
5685 // is the blockTranscribed which is the helper function for the
5686 // block literal; as in: self.c = ^() {[ace ARR];};
5687 bool saveDisableReplaceStmt = DisableReplaceStmt;
5688 DisableReplaceStmt = false;
5689 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
5690 DisableReplaceStmt = saveDisableReplaceStmt;
5691 CurrentBody = SaveCurrentBody;
5692 PropParentMap = 0;
5693 ImportedLocalExternalDecls.clear();
5694 // Now we snarf the rewritten text and stash it away for later use.
5695 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
5696 RewrittenBlockExprs[BE] = Str;
5697
5698 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5699
5700 //blockTranscribed->dump();
5701 ReplaceStmt(S, blockTranscribed);
5702 return blockTranscribed;
5703 }
5704 // Handle specific things.
5705 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5706 return RewriteAtEncode(AtEncode);
5707
5708 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5709 return RewriteAtSelector(AtSelector);
5710
5711 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5712 return RewriteObjCStringLiteral(AtString);
Fariborz Jahanian55947042012-03-27 20:17:30 +00005713
5714 if (ObjCBoolLiteralExpr *BoolLitExpr = dyn_cast<ObjCBoolLiteralExpr>(S))
5715 return RewriteObjCBoolLiteralExpr(BoolLitExpr);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00005716
Patrick Beardeb382ec2012-04-19 00:25:12 +00005717 if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(S))
5718 return RewriteObjCBoxedExpr(BoxedExpr);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00005719
5720 if (ObjCArrayLiteral *ArrayLitExpr = dyn_cast<ObjCArrayLiteral>(S))
5721 return RewriteObjCArrayLiteralExpr(ArrayLitExpr);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00005722
5723 if (ObjCDictionaryLiteral *DictionaryLitExpr =
5724 dyn_cast<ObjCDictionaryLiteral>(S))
5725 return RewriteObjCDictionaryLiteralExpr(DictionaryLitExpr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005726
5727 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
5728#if 0
5729 // Before we rewrite it, put the original message expression in a comment.
5730 SourceLocation startLoc = MessExpr->getLocStart();
5731 SourceLocation endLoc = MessExpr->getLocEnd();
5732
5733 const char *startBuf = SM->getCharacterData(startLoc);
5734 const char *endBuf = SM->getCharacterData(endLoc);
5735
5736 std::string messString;
5737 messString += "// ";
5738 messString.append(startBuf, endBuf-startBuf+1);
5739 messString += "\n";
5740
5741 // FIXME: Missing definition of
5742 // InsertText(clang::SourceLocation, char const*, unsigned int).
5743 // InsertText(startLoc, messString.c_str(), messString.size());
5744 // Tried this, but it didn't work either...
5745 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
5746#endif
5747 return RewriteMessageExpr(MessExpr);
5748 }
5749
Fariborz Jahanian042b91d2012-05-23 23:47:20 +00005750 if (ObjCAutoreleasePoolStmt *StmtAutoRelease =
5751 dyn_cast<ObjCAutoreleasePoolStmt>(S)) {
5752 return RewriteObjCAutoreleasePoolStmt(StmtAutoRelease);
5753 }
5754
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005755 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5756 return RewriteObjCTryStmt(StmtTry);
5757
5758 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5759 return RewriteObjCSynchronizedStmt(StmtTry);
5760
5761 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5762 return RewriteObjCThrowStmt(StmtThrow);
5763
5764 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5765 return RewriteObjCProtocolExpr(ProtocolExp);
5766
5767 if (ObjCForCollectionStmt *StmtForCollection =
5768 dyn_cast<ObjCForCollectionStmt>(S))
5769 return RewriteObjCForCollectionStmt(StmtForCollection,
5770 OrigStmtRange.getEnd());
5771 if (BreakStmt *StmtBreakStmt =
5772 dyn_cast<BreakStmt>(S))
5773 return RewriteBreakStmt(StmtBreakStmt);
5774 if (ContinueStmt *StmtContinueStmt =
5775 dyn_cast<ContinueStmt>(S))
5776 return RewriteContinueStmt(StmtContinueStmt);
5777
5778 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
5779 // and cast exprs.
5780 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5781 // FIXME: What we're doing here is modifying the type-specifier that
5782 // precedes the first Decl. In the future the DeclGroup should have
5783 // a separate type-specifier that we can rewrite.
5784 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5785 // the context of an ObjCForCollectionStmt. For example:
5786 // NSArray *someArray;
5787 // for (id <FooProtocol> index in someArray) ;
5788 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5789 // and it depends on the original text locations/positions.
5790 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
5791 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
5792
5793 // Blocks rewrite rules.
5794 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5795 DI != DE; ++DI) {
5796 Decl *SD = *DI;
5797 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
5798 if (isTopLevelBlockPointerType(ND->getType()))
5799 RewriteBlockPointerDecl(ND);
5800 else if (ND->getType()->isFunctionPointerType())
5801 CheckFunctionPointerDecl(ND->getType(), ND);
5802 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
5803 if (VD->hasAttr<BlocksAttr>()) {
5804 static unsigned uniqueByrefDeclCount = 0;
5805 assert(!BlockByRefDeclNo.count(ND) &&
5806 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5807 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00005808 RewriteByRefVar(VD, (DI == DS->decl_begin()), ((DI+1) == DE));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005809 }
5810 else
5811 RewriteTypeOfDecl(VD);
5812 }
5813 }
5814 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
5815 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5816 RewriteBlockPointerDecl(TD);
5817 else if (TD->getUnderlyingType()->isFunctionPointerType())
5818 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5819 }
5820 }
5821 }
5822
5823 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5824 RewriteObjCQualifiedInterfaceTypes(CE);
5825
5826 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5827 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5828 assert(!Stmts.empty() && "Statement stack is empty");
5829 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5830 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
5831 && "Statement stack mismatch");
5832 Stmts.pop_back();
5833 }
5834 // Handle blocks rewriting.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005835 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5836 ValueDecl *VD = DRE->getDecl();
5837 if (VD->hasAttr<BlocksAttr>())
5838 return RewriteBlockDeclRefExpr(DRE);
5839 if (HasLocalVariableExternalStorage(VD))
5840 return RewriteLocalVariableExternalStorage(DRE);
5841 }
5842
5843 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
5844 if (CE->getCallee()->getType()->isBlockPointerType()) {
5845 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
5846 ReplaceStmt(S, BlockCall);
5847 return BlockCall;
5848 }
5849 }
5850 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
5851 RewriteCastExpr(CE);
5852 }
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00005853 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5854 RewriteImplicitCastObjCExpr(ICE);
5855 }
Fariborz Jahanian43aa1c32012-04-16 22:14:01 +00005856#if 0
Fariborz Jahanian653b7cf2012-04-13 18:00:54 +00005857
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005858 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5859 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5860 ICE->getSubExpr(),
5861 SourceLocation());
5862 // Get the new text.
5863 std::string SStr;
5864 llvm::raw_string_ostream Buf(SStr);
Richard Smithd1420c62012-08-16 03:56:14 +00005865 Replacement->printPretty(Buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005866 const std::string &Str = Buf.str();
5867
5868 printf("CAST = %s\n", &Str[0]);
5869 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5870 delete S;
5871 return Replacement;
5872 }
5873#endif
5874 // Return this stmt unmodified.
5875 return S;
5876}
5877
5878void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
5879 for (RecordDecl::field_iterator i = RD->field_begin(),
5880 e = RD->field_end(); i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00005881 FieldDecl *FD = *i;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005882 if (isTopLevelBlockPointerType(FD->getType()))
5883 RewriteBlockPointerDecl(FD);
5884 if (FD->getType()->isObjCQualifiedIdType() ||
5885 FD->getType()->isObjCQualifiedInterfaceType())
5886 RewriteObjCQualifiedInterfaceTypes(FD);
5887 }
5888}
5889
5890/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5891/// main file of the input.
5892void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
5893 switch (D->getKind()) {
5894 case Decl::Function: {
5895 FunctionDecl *FD = cast<FunctionDecl>(D);
5896 if (FD->isOverloadedOperator())
5897 return;
5898
5899 // Since function prototypes don't have ParmDecl's, we check the function
5900 // prototype. This enables us to rewrite function declarations and
5901 // definitions using the same code.
5902 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
5903
Argyrios Kyrtzidis9335df32012-02-12 04:48:45 +00005904 if (!FD->isThisDeclarationADefinition())
5905 break;
5906
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005907 // FIXME: If this should support Obj-C++, support CXXTryStmt
5908 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
5909 CurFunctionDef = FD;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005910 CurrentBody = Body;
5911 Body =
5912 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5913 FD->setBody(Body);
5914 CurrentBody = 0;
5915 if (PropParentMap) {
5916 delete PropParentMap;
5917 PropParentMap = 0;
5918 }
5919 // This synthesizes and inserts the block "impl" struct, invoke function,
5920 // and any copy/dispose helper functions.
5921 InsertBlockLiteralsWithinFunction(FD);
Fariborz Jahanian96205962012-11-06 17:30:23 +00005922 RewriteLineDirective(D);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005923 CurFunctionDef = 0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005924 }
5925 break;
5926 }
5927 case Decl::ObjCMethod: {
5928 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
5929 if (CompoundStmt *Body = MD->getCompoundBody()) {
5930 CurMethodDef = MD;
5931 CurrentBody = Body;
5932 Body =
5933 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5934 MD->setBody(Body);
5935 CurrentBody = 0;
5936 if (PropParentMap) {
5937 delete PropParentMap;
5938 PropParentMap = 0;
5939 }
5940 InsertBlockLiteralsWithinMethod(MD);
Fariborz Jahanian96205962012-11-06 17:30:23 +00005941 RewriteLineDirective(D);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005942 CurMethodDef = 0;
5943 }
5944 break;
5945 }
5946 case Decl::ObjCImplementation: {
5947 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
5948 ClassImplementation.push_back(CI);
5949 break;
5950 }
5951 case Decl::ObjCCategoryImpl: {
5952 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
5953 CategoryImplementation.push_back(CI);
5954 break;
5955 }
5956 case Decl::Var: {
5957 VarDecl *VD = cast<VarDecl>(D);
5958 RewriteObjCQualifiedInterfaceTypes(VD);
5959 if (isTopLevelBlockPointerType(VD->getType()))
5960 RewriteBlockPointerDecl(VD);
5961 else if (VD->getType()->isFunctionPointerType()) {
5962 CheckFunctionPointerDecl(VD->getType(), VD);
5963 if (VD->getInit()) {
5964 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5965 RewriteCastExpr(CE);
5966 }
5967 }
5968 } else if (VD->getType()->isRecordType()) {
5969 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5970 if (RD->isCompleteDefinition())
5971 RewriteRecordBody(RD);
5972 }
5973 if (VD->getInit()) {
5974 GlobalVarDecl = VD;
5975 CurrentBody = VD->getInit();
5976 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
5977 CurrentBody = 0;
5978 if (PropParentMap) {
5979 delete PropParentMap;
5980 PropParentMap = 0;
5981 }
5982 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
5983 GlobalVarDecl = 0;
5984
5985 // This is needed for blocks.
5986 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5987 RewriteCastExpr(CE);
5988 }
5989 }
5990 break;
5991 }
5992 case Decl::TypeAlias:
5993 case Decl::Typedef: {
5994 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
5995 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5996 RewriteBlockPointerDecl(TD);
5997 else if (TD->getUnderlyingType()->isFunctionPointerType())
5998 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5999 }
6000 break;
6001 }
6002 case Decl::CXXRecord:
6003 case Decl::Record: {
6004 RecordDecl *RD = cast<RecordDecl>(D);
6005 if (RD->isCompleteDefinition())
6006 RewriteRecordBody(RD);
6007 break;
6008 }
6009 default:
6010 break;
6011 }
6012 // Nothing yet.
6013}
6014
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006015/// Write_ProtocolExprReferencedMetadata - This routine writer out the
6016/// protocol reference symbols in the for of:
6017/// struct _protocol_t *PROTOCOL_REF = &PROTOCOL_METADATA.
6018static void Write_ProtocolExprReferencedMetadata(ASTContext *Context,
6019 ObjCProtocolDecl *PDecl,
6020 std::string &Result) {
6021 // Also output .objc_protorefs$B section and its meta-data.
6022 if (Context->getLangOpts().MicrosoftExt)
Fariborz Jahanianbd78cfa2012-04-27 21:39:49 +00006023 Result += "static ";
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006024 Result += "struct _protocol_t *";
6025 Result += "_OBJC_PROTOCOL_REFERENCE_$_";
6026 Result += PDecl->getNameAsString();
6027 Result += " = &";
6028 Result += "_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
6029 Result += ";\n";
6030}
6031
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006032void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
6033 if (Diags.hasErrorOccurred())
6034 return;
6035
6036 RewriteInclude();
6037
Fariborz Jahanian31c4a4b2013-02-07 22:50:40 +00006038 for (unsigned i = 0, e = FunctionDefinitionsSeen.size(); i < e; i++) {
6039 // translation of function bodies were postponed untill all class and
6040 // their extensions and implementations are seen. This is because, we
6041 // cannot build grouping structs for bitfields untill they are all seen.
6042 FunctionDecl *FDecl = FunctionDefinitionsSeen[i];
6043 HandleTopLevelSingleDecl(FDecl);
6044 }
6045
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006046 // Here's a great place to add any extra declarations that may be needed.
6047 // Write out meta data for each @protocol(<expr>).
6048 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006049 E = ProtocolExprDecls.end(); I != E; ++I) {
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006050 RewriteObjCProtocolMetaData(*I, Preamble);
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006051 Write_ProtocolExprReferencedMetadata(Context, (*I), Preamble);
6052 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006053
6054 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +00006055
6056 if (ClassImplementation.size() || CategoryImplementation.size())
6057 RewriteImplementations();
6058
Fariborz Jahanian57317782012-02-21 23:58:41 +00006059 for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) {
6060 ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i];
6061 // Write struct declaration for the class matching its ivar declarations.
6062 // Note that for modern abi, this is postponed until the end of TU
6063 // because class extensions and the implementation might declare their own
6064 // private ivars.
6065 RewriteInterfaceDecl(CDecl);
6066 }
Fariborz Jahanian31c4a4b2013-02-07 22:50:40 +00006067
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006068 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
6069 // we are done.
6070 if (const RewriteBuffer *RewriteBuf =
6071 Rewrite.getRewriteBufferFor(MainFileID)) {
6072 //printf("Changed:\n");
6073 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
6074 } else {
6075 llvm::errs() << "No changes\n";
6076 }
6077
6078 if (ClassImplementation.size() || CategoryImplementation.size() ||
6079 ProtocolExprDecls.size()) {
6080 // Rewrite Objective-c meta data*
6081 std::string ResultStr;
6082 RewriteMetaDataIntoBuffer(ResultStr);
6083 // Emit metadata.
6084 *OutFile << ResultStr;
6085 }
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006086 // Emit ImageInfo;
6087 {
6088 std::string ResultStr;
6089 WriteImageInfo(ResultStr);
6090 *OutFile << ResultStr;
6091 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006092 OutFile->flush();
6093}
6094
6095void RewriteModernObjC::Initialize(ASTContext &context) {
6096 InitializeCommon(context);
6097
Fariborz Jahanian6991bc52012-03-10 17:45:38 +00006098 Preamble += "#ifndef __OBJC2__\n";
6099 Preamble += "#define __OBJC2__\n";
6100 Preamble += "#endif\n";
6101
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006102 // declaring objc_selector outside the parameter list removes a silly
6103 // scope related warning...
6104 if (IsHeader)
6105 Preamble = "#pragma once\n";
6106 Preamble += "struct objc_selector; struct objc_class;\n";
Fariborz Jahaniane2d87bc2012-04-12 23:52:52 +00006107 Preamble += "struct __rw_objc_super { \n\tstruct objc_object *object; ";
6108 Preamble += "\n\tstruct objc_object *superClass; ";
6109 // Add a constructor for creating temporary objects.
6110 Preamble += "\n\t__rw_objc_super(struct objc_object *o, struct objc_object *s) ";
6111 Preamble += ": object(o), superClass(s) {} ";
6112 Preamble += "\n};\n";
6113
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006114 if (LangOpts.MicrosoftExt) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006115 // Define all sections using syntax that makes sense.
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006116 // These are currently generated.
6117 Preamble += "\n#pragma section(\".objc_classlist$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006118 Preamble += "#pragma section(\".objc_catlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006119 Preamble += "#pragma section(\".objc_imageinfo$B\", long, read, write)\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006120 Preamble += "#pragma section(\".objc_nlclslist$B\", long, read, write)\n";
6121 Preamble += "#pragma section(\".objc_nlcatlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006122 // These are generated but not necessary for functionality.
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006123 Preamble += "#pragma section(\".cat_cls_meth$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006124 Preamble += "#pragma section(\".inst_meth$B\", long, read, write)\n";
6125 Preamble += "#pragma section(\".cls_meth$B\", long, read, write)\n";
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00006126 Preamble += "#pragma section(\".objc_ivar$B\", long, read, write)\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006127
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006128 // These need be generated for performance. Currently they are not,
6129 // using API calls instead.
6130 Preamble += "#pragma section(\".objc_selrefs$B\", long, read, write)\n";
6131 Preamble += "#pragma section(\".objc_classrefs$B\", long, read, write)\n";
6132 Preamble += "#pragma section(\".objc_superrefs$B\", long, read, write)\n";
6133
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006134 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006135 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
6136 Preamble += "typedef struct objc_object Protocol;\n";
6137 Preamble += "#define _REWRITER_typedef_Protocol\n";
6138 Preamble += "#endif\n";
6139 if (LangOpts.MicrosoftExt) {
6140 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
6141 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
Fariborz Jahanian5cf6b6c2012-03-21 23:41:04 +00006142 }
6143 else
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006144 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Fariborz Jahanian5cf6b6c2012-03-21 23:41:04 +00006145
6146 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend(void);\n";
6147 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper(void);\n";
6148 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_stret(void);\n";
6149 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper_stret(void);\n";
6150 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_fpret(void);\n";
6151
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00006152 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getClass";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006153 Preamble += "(const char *);\n";
6154 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
6155 Preamble += "(struct objc_class *);\n";
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00006156 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getMetaClass";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006157 Preamble += "(const char *);\n";
Fariborz Jahanian55261af2012-03-19 18:11:32 +00006158 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw( struct objc_object *);\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006159 // @synchronized hooks.
Aaron Ballman2d234d732012-09-06 16:44:16 +00006160 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_enter( struct objc_object *);\n";
6161 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_exit( struct objc_object *);\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006162 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
6163 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
6164 Preamble += "struct __objcFastEnumerationState {\n\t";
6165 Preamble += "unsigned long state;\n\t";
6166 Preamble += "void **itemsPtr;\n\t";
6167 Preamble += "unsigned long *mutationsPtr;\n\t";
6168 Preamble += "unsigned long extra[5];\n};\n";
6169 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
6170 Preamble += "#define __FASTENUMERATIONSTATE\n";
6171 Preamble += "#endif\n";
6172 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
6173 Preamble += "struct __NSConstantStringImpl {\n";
6174 Preamble += " int *isa;\n";
6175 Preamble += " int flags;\n";
6176 Preamble += " char *str;\n";
6177 Preamble += " long length;\n";
6178 Preamble += "};\n";
6179 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
6180 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
6181 Preamble += "#else\n";
6182 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
6183 Preamble += "#endif\n";
6184 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
6185 Preamble += "#endif\n";
6186 // Blocks preamble.
6187 Preamble += "#ifndef BLOCK_IMPL\n";
6188 Preamble += "#define BLOCK_IMPL\n";
6189 Preamble += "struct __block_impl {\n";
6190 Preamble += " void *isa;\n";
6191 Preamble += " int Flags;\n";
6192 Preamble += " int Reserved;\n";
6193 Preamble += " void *FuncPtr;\n";
6194 Preamble += "};\n";
6195 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
6196 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
6197 Preamble += "extern \"C\" __declspec(dllexport) "
6198 "void _Block_object_assign(void *, const void *, const int);\n";
6199 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
6200 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
6201 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
6202 Preamble += "#else\n";
6203 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
6204 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
6205 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
6206 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
6207 Preamble += "#endif\n";
6208 Preamble += "#endif\n";
6209 if (LangOpts.MicrosoftExt) {
6210 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
6211 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
6212 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
6213 Preamble += "#define __attribute__(X)\n";
6214 Preamble += "#endif\n";
Fariborz Jahanian5ce28272012-04-12 16:33:31 +00006215 Preamble += "#ifndef __weak\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006216 Preamble += "#define __weak\n";
Fariborz Jahanian5ce28272012-04-12 16:33:31 +00006217 Preamble += "#endif\n";
6218 Preamble += "#ifndef __block\n";
6219 Preamble += "#define __block\n";
6220 Preamble += "#endif\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006221 }
6222 else {
6223 Preamble += "#define __block\n";
6224 Preamble += "#define __weak\n";
6225 }
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00006226
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00006227 // Declarations required for modern objective-c array and dictionary literals.
6228 Preamble += "\n#include <stdarg.h>\n";
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00006229 Preamble += "struct __NSContainer_literal {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00006230 Preamble += " void * *arr;\n";
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00006231 Preamble += " __NSContainer_literal (unsigned int count, ...) {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00006232 Preamble += "\tva_list marker;\n";
6233 Preamble += "\tva_start(marker, count);\n";
6234 Preamble += "\tarr = new void *[count];\n";
6235 Preamble += "\tfor (unsigned i = 0; i < count; i++)\n";
6236 Preamble += "\t arr[i] = va_arg(marker, void *);\n";
6237 Preamble += "\tva_end( marker );\n";
6238 Preamble += " };\n";
Fariborz Jahanian13a9c022012-05-02 23:53:46 +00006239 Preamble += " ~__NSContainer_literal() {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00006240 Preamble += "\tdelete[] arr;\n";
6241 Preamble += " }\n";
6242 Preamble += "};\n";
6243
Fariborz Jahanian042b91d2012-05-23 23:47:20 +00006244 // Declaration required for implementation of @autoreleasepool statement.
6245 Preamble += "extern \"C\" __declspec(dllimport) void * objc_autoreleasePoolPush(void);\n";
6246 Preamble += "extern \"C\" __declspec(dllimport) void objc_autoreleasePoolPop(void *);\n\n";
6247 Preamble += "struct __AtAutoreleasePool {\n";
6248 Preamble += " __AtAutoreleasePool() {atautoreleasepoolobj = objc_autoreleasePoolPush();}\n";
6249 Preamble += " ~__AtAutoreleasePool() {objc_autoreleasePoolPop(atautoreleasepoolobj);}\n";
6250 Preamble += " void * atautoreleasepoolobj;\n";
6251 Preamble += "};\n";
6252
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006253 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
6254 // as this avoids warning in any 64bit/32bit compilation model.
6255 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
6256}
6257
6258/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
6259/// ivar offset.
6260void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
6261 std::string &Result) {
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00006262 Result += "__OFFSETOFIVAR__(struct ";
6263 Result += ivar->getContainingInterface()->getNameAsString();
6264 if (LangOpts.MicrosoftExt)
6265 Result += "_IMPL";
6266 Result += ", ";
6267 if (ivar->isBitField())
6268 ObjCIvarBitfieldGroupDecl(ivar, Result);
6269 else
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006270 Result += ivar->getNameAsString();
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00006271 Result += ")";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006272}
6273
6274/// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
6275/// struct _prop_t {
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006276/// const char *name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006277/// char *attributes;
6278/// }
6279
6280/// struct _prop_list_t {
6281/// uint32_t entsize; // sizeof(struct _prop_t)
6282/// uint32_t count_of_properties;
6283/// struct _prop_t prop_list[count_of_properties];
6284/// }
6285
6286/// struct _protocol_t;
6287
6288/// struct _protocol_list_t {
6289/// long protocol_count; // Note, this is 32/64 bit
6290/// struct _protocol_t * protocol_list[protocol_count];
6291/// }
6292
6293/// struct _objc_method {
6294/// SEL _cmd;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006295/// const char *method_type;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006296/// char *_imp;
6297/// }
6298
6299/// struct _method_list_t {
6300/// uint32_t entsize; // sizeof(struct _objc_method)
6301/// uint32_t method_count;
6302/// struct _objc_method method_list[method_count];
6303/// }
6304
6305/// struct _protocol_t {
6306/// id isa; // NULL
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006307/// const char *protocol_name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006308/// const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006309/// const struct method_list_t *instance_methods;
6310/// const struct method_list_t *class_methods;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006311/// const struct method_list_t *optionalInstanceMethods;
6312/// const struct method_list_t *optionalClassMethods;
6313/// const struct _prop_list_t * properties;
6314/// const uint32_t size; // sizeof(struct _protocol_t)
6315/// const uint32_t flags; // = 0
6316/// const char ** extendedMethodTypes;
6317/// }
6318
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006319/// struct _ivar_t {
6320/// unsigned long int *offset; // pointer to ivar offset location
Fariborz Jahanianae932952012-02-10 20:47:10 +00006321/// const char *name;
6322/// const char *type;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006323/// uint32_t alignment;
6324/// uint32_t size;
6325/// }
6326
6327/// struct _ivar_list_t {
6328/// uint32 entsize; // sizeof(struct _ivar_t)
6329/// uint32 count;
Fariborz Jahanianae932952012-02-10 20:47:10 +00006330/// struct _ivar_t list[count];
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006331/// }
6332
6333/// struct _class_ro_t {
Fariborz Jahanian249cd102012-03-24 16:53:16 +00006334/// uint32_t flags;
6335/// uint32_t instanceStart;
6336/// uint32_t instanceSize;
6337/// uint32_t reserved; // only when building for 64bit targets
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006338/// const uint8_t *ivarLayout;
6339/// const char *name;
6340/// const struct _method_list_t *baseMethods;
6341/// const struct _protocol_list_t *baseProtocols;
6342/// const struct _ivar_list_t *ivars;
6343/// const uint8_t *weakIvarLayout;
6344/// const struct _prop_list_t *properties;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006345/// }
6346
6347/// struct _class_t {
6348/// struct _class_t *isa;
Fariborz Jahanianfd4ce2c2012-03-20 17:34:50 +00006349/// struct _class_t *superclass;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006350/// void *cache;
6351/// IMP *vtable;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006352/// struct _class_ro_t *ro;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006353/// }
6354
6355/// struct _category_t {
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006356/// const char *name;
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006357/// struct _class_t *cls;
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006358/// const struct _method_list_t *instance_methods;
6359/// const struct _method_list_t *class_methods;
6360/// const struct _protocol_list_t *protocols;
6361/// const struct _prop_list_t *properties;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006362/// }
6363
6364/// MessageRefTy - LLVM for:
6365/// struct _message_ref_t {
6366/// IMP messenger;
6367/// SEL name;
6368/// };
6369
6370/// SuperMessageRefTy - LLVM for:
6371/// struct _super_message_ref_t {
6372/// SUPER_IMP messenger;
6373/// SEL name;
6374/// };
6375
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006376static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006377 static bool meta_data_declared = false;
6378 if (meta_data_declared)
6379 return;
6380
6381 Result += "\nstruct _prop_t {\n";
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006382 Result += "\tconst char *name;\n";
6383 Result += "\tconst char *attributes;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006384 Result += "};\n";
6385
6386 Result += "\nstruct _protocol_t;\n";
6387
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006388 Result += "\nstruct _objc_method {\n";
6389 Result += "\tstruct objc_selector * _cmd;\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006390 Result += "\tconst char *method_type;\n";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006391 Result += "\tvoid *_imp;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006392 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006393
6394 Result += "\nstruct _protocol_t {\n";
6395 Result += "\tvoid * isa; // NULL\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006396 Result += "\tconst char *protocol_name;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006397 Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006398 Result += "\tconst struct method_list_t *instance_methods;\n";
6399 Result += "\tconst struct method_list_t *class_methods;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006400 Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
6401 Result += "\tconst struct method_list_t *optionalClassMethods;\n";
6402 Result += "\tconst struct _prop_list_t * properties;\n";
6403 Result += "\tconst unsigned int size; // sizeof(struct _protocol_t)\n";
6404 Result += "\tconst unsigned int flags; // = 0\n";
6405 Result += "\tconst char ** extendedMethodTypes;\n";
6406 Result += "};\n";
6407
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006408 Result += "\nstruct _ivar_t {\n";
6409 Result += "\tunsigned long int *offset; // pointer to ivar offset location\n";
Fariborz Jahanianae932952012-02-10 20:47:10 +00006410 Result += "\tconst char *name;\n";
6411 Result += "\tconst char *type;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006412 Result += "\tunsigned int alignment;\n";
6413 Result += "\tunsigned int size;\n";
6414 Result += "};\n";
6415
6416 Result += "\nstruct _class_ro_t {\n";
Fariborz Jahanian249cd102012-03-24 16:53:16 +00006417 Result += "\tunsigned int flags;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006418 Result += "\tunsigned int instanceStart;\n";
Fariborz Jahanian249cd102012-03-24 16:53:16 +00006419 Result += "\tunsigned int instanceSize;\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006420 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6421 if (Triple.getArch() == llvm::Triple::x86_64)
Fariborz Jahanian249cd102012-03-24 16:53:16 +00006422 Result += "\tunsigned int reserved;\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006423 Result += "\tconst unsigned char *ivarLayout;\n";
6424 Result += "\tconst char *name;\n";
6425 Result += "\tconst struct _method_list_t *baseMethods;\n";
6426 Result += "\tconst struct _objc_protocol_list *baseProtocols;\n";
6427 Result += "\tconst struct _ivar_list_t *ivars;\n";
6428 Result += "\tconst unsigned char *weakIvarLayout;\n";
6429 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006430 Result += "};\n";
6431
6432 Result += "\nstruct _class_t {\n";
6433 Result += "\tstruct _class_t *isa;\n";
Fariborz Jahanianfd4ce2c2012-03-20 17:34:50 +00006434 Result += "\tstruct _class_t *superclass;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006435 Result += "\tvoid *cache;\n";
6436 Result += "\tvoid *vtable;\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006437 Result += "\tstruct _class_ro_t *ro;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006438 Result += "};\n";
6439
6440 Result += "\nstruct _category_t {\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006441 Result += "\tconst char *name;\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006442 Result += "\tstruct _class_t *cls;\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006443 Result += "\tconst struct _method_list_t *instance_methods;\n";
6444 Result += "\tconst struct _method_list_t *class_methods;\n";
6445 Result += "\tconst struct _protocol_list_t *protocols;\n";
6446 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006447 Result += "};\n";
6448
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006449 Result += "extern \"C\" __declspec(dllimport) struct objc_cache _objc_empty_cache;\n";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006450 Result += "#pragma warning(disable:4273)\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006451 meta_data_declared = true;
6452}
6453
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006454static void Write_protocol_list_t_TypeDecl(std::string &Result,
6455 long super_protocol_count) {
6456 Result += "struct /*_protocol_list_t*/"; Result += " {\n";
6457 Result += "\tlong protocol_count; // Note, this is 32/64 bit\n";
6458 Result += "\tstruct _protocol_t *super_protocols[";
6459 Result += utostr(super_protocol_count); Result += "];\n";
6460 Result += "}";
6461}
6462
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006463static void Write_method_list_t_TypeDecl(std::string &Result,
6464 unsigned int method_count) {
6465 Result += "struct /*_method_list_t*/"; Result += " {\n";
6466 Result += "\tunsigned int entsize; // sizeof(struct _objc_method)\n";
6467 Result += "\tunsigned int method_count;\n";
6468 Result += "\tstruct _objc_method method_list[";
6469 Result += utostr(method_count); Result += "];\n";
6470 Result += "}";
6471}
6472
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006473static void Write__prop_list_t_TypeDecl(std::string &Result,
6474 unsigned int property_count) {
6475 Result += "struct /*_prop_list_t*/"; Result += " {\n";
6476 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6477 Result += "\tunsigned int count_of_properties;\n";
6478 Result += "\tstruct _prop_t prop_list[";
6479 Result += utostr(property_count); Result += "];\n";
6480 Result += "}";
6481}
6482
Fariborz Jahanianae932952012-02-10 20:47:10 +00006483static void Write__ivar_list_t_TypeDecl(std::string &Result,
6484 unsigned int ivar_count) {
6485 Result += "struct /*_ivar_list_t*/"; Result += " {\n";
6486 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6487 Result += "\tunsigned int count;\n";
6488 Result += "\tstruct _ivar_t ivar_list[";
6489 Result += utostr(ivar_count); Result += "];\n";
6490 Result += "}";
6491}
6492
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006493static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result,
6494 ArrayRef<ObjCProtocolDecl *> SuperProtocols,
6495 StringRef VarName,
6496 StringRef ProtocolName) {
6497 if (SuperProtocols.size() > 0) {
6498 Result += "\nstatic ";
6499 Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size());
6500 Result += " "; Result += VarName;
6501 Result += ProtocolName;
6502 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6503 Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n";
6504 for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) {
6505 ObjCProtocolDecl *SuperPD = SuperProtocols[i];
6506 Result += "\t&"; Result += "_OBJC_PROTOCOL_";
6507 Result += SuperPD->getNameAsString();
6508 if (i == e-1)
6509 Result += "\n};\n";
6510 else
6511 Result += ",\n";
6512 }
6513 }
6514}
6515
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006516static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj,
6517 ASTContext *Context, std::string &Result,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006518 ArrayRef<ObjCMethodDecl *> Methods,
6519 StringRef VarName,
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006520 StringRef TopLevelDeclName,
6521 bool MethodImpl) {
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006522 if (Methods.size() > 0) {
6523 Result += "\nstatic ";
6524 Write_method_list_t_TypeDecl(Result, Methods.size());
6525 Result += " "; Result += VarName;
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006526 Result += TopLevelDeclName;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006527 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6528 Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
6529 Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
6530 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6531 ObjCMethodDecl *MD = Methods[i];
6532 if (i == 0)
6533 Result += "\t{{(struct objc_selector *)\"";
6534 else
6535 Result += "\t{(struct objc_selector *)\"";
6536 Result += (MD)->getSelector().getAsString(); Result += "\"";
6537 Result += ", ";
6538 std::string MethodTypeString;
6539 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString);
6540 Result += "\""; Result += MethodTypeString; Result += "\"";
6541 Result += ", ";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006542 if (!MethodImpl)
6543 Result += "0";
6544 else {
6545 Result += "(void *)";
6546 Result += RewriteObj.MethodInternalNames[MD];
6547 }
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006548 if (i == e-1)
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006549 Result += "}}\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006550 else
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006551 Result += "},\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006552 }
6553 Result += "};\n";
6554 }
6555}
6556
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006557static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006558 ASTContext *Context, std::string &Result,
6559 ArrayRef<ObjCPropertyDecl *> Properties,
6560 const Decl *Container,
6561 StringRef VarName,
6562 StringRef ProtocolName) {
6563 if (Properties.size() > 0) {
6564 Result += "\nstatic ";
6565 Write__prop_list_t_TypeDecl(Result, Properties.size());
6566 Result += " "; Result += VarName;
6567 Result += ProtocolName;
6568 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6569 Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
6570 Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
6571 for (unsigned i = 0, e = Properties.size(); i < e; i++) {
6572 ObjCPropertyDecl *PropDecl = Properties[i];
6573 if (i == 0)
6574 Result += "\t{{\"";
6575 else
6576 Result += "\t{\"";
6577 Result += PropDecl->getName(); Result += "\",";
6578 std::string PropertyTypeString, QuotePropertyTypeString;
6579 Context->getObjCEncodingForPropertyDecl(PropDecl, Container, PropertyTypeString);
6580 RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
6581 Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
6582 if (i == e-1)
6583 Result += "}}\n";
6584 else
6585 Result += "},\n";
6586 }
6587 Result += "};\n";
6588 }
6589}
6590
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006591// Metadata flags
6592enum MetaDataDlags {
6593 CLS = 0x0,
6594 CLS_META = 0x1,
6595 CLS_ROOT = 0x2,
6596 OBJC2_CLS_HIDDEN = 0x10,
6597 CLS_EXCEPTION = 0x20,
6598
6599 /// (Obsolete) ARC-specific: this class has a .release_ivars method
6600 CLS_HAS_IVAR_RELEASER = 0x40,
6601 /// class was compiled with -fobjc-arr
6602 CLS_COMPILED_BY_ARC = 0x80 // (1<<7)
6603};
6604
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006605static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result,
6606 unsigned int flags,
6607 const std::string &InstanceStart,
6608 const std::string &InstanceSize,
6609 ArrayRef<ObjCMethodDecl *>baseMethods,
6610 ArrayRef<ObjCProtocolDecl *>baseProtocols,
6611 ArrayRef<ObjCIvarDecl *>ivars,
6612 ArrayRef<ObjCPropertyDecl *>Properties,
6613 StringRef VarName,
6614 StringRef ClassName) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006615 Result += "\nstatic struct _class_ro_t ";
6616 Result += VarName; Result += ClassName;
6617 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6618 Result += "\t";
6619 Result += llvm::utostr(flags); Result += ", ";
6620 Result += InstanceStart; Result += ", ";
6621 Result += InstanceSize; Result += ", \n";
6622 Result += "\t";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006623 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6624 if (Triple.getArch() == llvm::Triple::x86_64)
6625 // uint32_t const reserved; // only when building for 64bit targets
6626 Result += "(unsigned int)0, \n\t";
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006627 // const uint8_t * const ivarLayout;
6628 Result += "0, \n\t";
6629 Result += "\""; Result += ClassName; Result += "\",\n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006630 bool metaclass = ((flags & CLS_META) != 0);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006631 if (baseMethods.size() > 0) {
6632 Result += "(const struct _method_list_t *)&";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006633 if (metaclass)
6634 Result += "_OBJC_$_CLASS_METHODS_";
6635 else
6636 Result += "_OBJC_$_INSTANCE_METHODS_";
6637 Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006638 Result += ",\n\t";
6639 }
6640 else
6641 Result += "0, \n\t";
6642
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006643 if (!metaclass && baseProtocols.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006644 Result += "(const struct _objc_protocol_list *)&";
6645 Result += "_OBJC_CLASS_PROTOCOLS_$_"; Result += ClassName;
6646 Result += ",\n\t";
6647 }
6648 else
6649 Result += "0, \n\t";
6650
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006651 if (!metaclass && ivars.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006652 Result += "(const struct _ivar_list_t *)&";
6653 Result += "_OBJC_$_INSTANCE_VARIABLES_"; Result += ClassName;
6654 Result += ",\n\t";
6655 }
6656 else
6657 Result += "0, \n\t";
6658
6659 // weakIvarLayout
6660 Result += "0, \n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006661 if (!metaclass && Properties.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006662 Result += "(const struct _prop_list_t *)&";
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00006663 Result += "_OBJC_$_PROP_LIST_"; Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006664 Result += ",\n";
6665 }
6666 else
6667 Result += "0, \n";
6668
6669 Result += "};\n";
6670}
6671
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006672static void Write_class_t(ASTContext *Context, std::string &Result,
6673 StringRef VarName,
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006674 const ObjCInterfaceDecl *CDecl, bool metaclass) {
6675 bool rootClass = (!CDecl->getSuperClass());
6676 const ObjCInterfaceDecl *RootClass = CDecl;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006677
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006678 if (!rootClass) {
6679 // Find the Root class
6680 RootClass = CDecl->getSuperClass();
6681 while (RootClass->getSuperClass()) {
6682 RootClass = RootClass->getSuperClass();
6683 }
6684 }
6685
6686 if (metaclass && rootClass) {
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006687 // Need to handle a case of use of forward declaration.
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006688 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006689 Result += "extern \"C\" ";
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006690 if (CDecl->getImplementation())
6691 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006692 else
6693 Result += "__declspec(dllimport) ";
6694
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006695 Result += "struct _class_t OBJC_CLASS_$_";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006696 Result += CDecl->getNameAsString();
6697 Result += ";\n";
6698 }
6699 // Also, for possibility of 'super' metadata class not having been defined yet.
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006700 if (!rootClass) {
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006701 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006702 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006703 Result += "extern \"C\" ";
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006704 if (SuperClass->getImplementation())
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006705 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006706 else
6707 Result += "__declspec(dllimport) ";
6708
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006709 Result += "struct _class_t ";
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006710 Result += VarName;
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006711 Result += SuperClass->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006712 Result += ";\n";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006713
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006714 if (metaclass && RootClass != SuperClass) {
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006715 Result += "extern \"C\" ";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006716 if (RootClass->getImplementation())
6717 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006718 else
6719 Result += "__declspec(dllimport) ";
6720
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006721 Result += "struct _class_t ";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006722 Result += VarName;
6723 Result += RootClass->getNameAsString();
6724 Result += ";\n";
6725 }
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006726 }
6727
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006728 Result += "\nextern \"C\" __declspec(dllexport) struct _class_t ";
6729 Result += VarName; Result += CDecl->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006730 Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n";
6731 Result += "\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006732 if (metaclass) {
6733 if (!rootClass) {
6734 Result += "0, // &"; Result += VarName;
6735 Result += RootClass->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006736 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006737 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006738 Result += CDecl->getSuperClass()->getNameAsString();
6739 Result += ",\n\t";
6740 }
6741 else {
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006742 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006743 Result += CDecl->getNameAsString();
6744 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006745 Result += "0, // &OBJC_CLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006746 Result += ",\n\t";
6747 }
6748 }
6749 else {
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006750 Result += "0, // &OBJC_METACLASS_$_";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006751 Result += CDecl->getNameAsString();
6752 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006753 if (!rootClass) {
6754 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006755 Result += CDecl->getSuperClass()->getNameAsString();
6756 Result += ",\n\t";
6757 }
6758 else
6759 Result += "0,\n\t";
6760 }
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006761 Result += "0, // (void *)&_objc_empty_cache,\n\t";
6762 Result += "0, // unused, was (void *)&_objc_empty_vtable,\n\t";
6763 if (metaclass)
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006764 Result += "&_OBJC_METACLASS_RO_$_";
6765 else
6766 Result += "&_OBJC_CLASS_RO_$_";
6767 Result += CDecl->getNameAsString();
6768 Result += ",\n};\n";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006769
6770 // Add static function to initialize some of the meta-data fields.
6771 // avoid doing it twice.
6772 if (metaclass)
6773 return;
6774
6775 const ObjCInterfaceDecl *SuperClass =
6776 rootClass ? CDecl : CDecl->getSuperClass();
6777
6778 Result += "static void OBJC_CLASS_SETUP_$_";
6779 Result += CDecl->getNameAsString();
6780 Result += "(void ) {\n";
6781 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6782 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006783 Result += RootClass->getNameAsString(); Result += ";\n";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006784
6785 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006786 Result += ".superclass = ";
6787 if (rootClass)
6788 Result += "&OBJC_CLASS_$_";
6789 else
6790 Result += "&OBJC_METACLASS_$_";
6791
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006792 Result += SuperClass->getNameAsString(); Result += ";\n";
6793
6794 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6795 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6796
6797 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6798 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
6799 Result += CDecl->getNameAsString(); Result += ";\n";
6800
6801 if (!rootClass) {
6802 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6803 Result += ".superclass = "; Result += "&OBJC_CLASS_$_";
6804 Result += SuperClass->getNameAsString(); Result += ";\n";
6805 }
6806
6807 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6808 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6809 Result += "}\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006810}
6811
Fariborz Jahanian61186122012-02-17 18:40:41 +00006812static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context,
6813 std::string &Result,
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006814 ObjCCategoryDecl *CatDecl,
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006815 ObjCInterfaceDecl *ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00006816 ArrayRef<ObjCMethodDecl *> InstanceMethods,
6817 ArrayRef<ObjCMethodDecl *> ClassMethods,
6818 ArrayRef<ObjCProtocolDecl *> RefedProtocols,
6819 ArrayRef<ObjCPropertyDecl *> ClassProperties) {
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006820 StringRef CatName = CatDecl->getName();
NAKAMURA Takumi20f89392012-03-21 03:21:46 +00006821 StringRef ClassName = ClassDecl->getName();
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00006822 // must declare an extern class object in case this class is not implemented
6823 // in this TU.
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006824 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006825 Result += "extern \"C\" ";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006826 if (ClassDecl->getImplementation())
6827 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006828 else
6829 Result += "__declspec(dllimport) ";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006830
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006831 Result += "struct _class_t ";
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00006832 Result += "OBJC_CLASS_$_"; Result += ClassName;
6833 Result += ";\n";
6834
Fariborz Jahanian61186122012-02-17 18:40:41 +00006835 Result += "\nstatic struct _category_t ";
6836 Result += "_OBJC_$_CATEGORY_";
6837 Result += ClassName; Result += "_$_"; Result += CatName;
6838 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6839 Result += "{\n";
6840 Result += "\t\""; Result += ClassName; Result += "\",\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006841 Result += "\t0, // &"; Result += "OBJC_CLASS_$_"; Result += ClassName;
Fariborz Jahanian61186122012-02-17 18:40:41 +00006842 Result += ",\n";
6843 if (InstanceMethods.size() > 0) {
6844 Result += "\t(const struct _method_list_t *)&";
6845 Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_";
6846 Result += ClassName; Result += "_$_"; Result += CatName;
6847 Result += ",\n";
6848 }
6849 else
6850 Result += "\t0,\n";
6851
6852 if (ClassMethods.size() > 0) {
6853 Result += "\t(const struct _method_list_t *)&";
6854 Result += "_OBJC_$_CATEGORY_CLASS_METHODS_";
6855 Result += ClassName; Result += "_$_"; Result += CatName;
6856 Result += ",\n";
6857 }
6858 else
6859 Result += "\t0,\n";
6860
6861 if (RefedProtocols.size() > 0) {
6862 Result += "\t(const struct _protocol_list_t *)&";
6863 Result += "_OBJC_CATEGORY_PROTOCOLS_$_";
6864 Result += ClassName; Result += "_$_"; Result += CatName;
6865 Result += ",\n";
6866 }
6867 else
6868 Result += "\t0,\n";
6869
6870 if (ClassProperties.size() > 0) {
6871 Result += "\t(const struct _prop_list_t *)&"; Result += "_OBJC_$_PROP_LIST_";
6872 Result += ClassName; Result += "_$_"; Result += CatName;
6873 Result += ",\n";
6874 }
6875 else
6876 Result += "\t0,\n";
6877
6878 Result += "};\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006879
6880 // Add static function to initialize the class pointer in the category structure.
6881 Result += "static void OBJC_CATEGORY_SETUP_$_";
6882 Result += ClassDecl->getNameAsString();
6883 Result += "_$_";
6884 Result += CatName;
6885 Result += "(void ) {\n";
6886 Result += "\t_OBJC_$_CATEGORY_";
6887 Result += ClassDecl->getNameAsString();
6888 Result += "_$_";
6889 Result += CatName;
6890 Result += ".cls = "; Result += "&OBJC_CLASS_$_"; Result += ClassName;
6891 Result += ";\n}\n";
Fariborz Jahanian61186122012-02-17 18:40:41 +00006892}
6893
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006894static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj,
6895 ASTContext *Context, std::string &Result,
6896 ArrayRef<ObjCMethodDecl *> Methods,
6897 StringRef VarName,
6898 StringRef ProtocolName) {
6899 if (Methods.size() == 0)
6900 return;
6901
6902 Result += "\nstatic const char *";
6903 Result += VarName; Result += ProtocolName;
6904 Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6905 Result += "{\n";
6906 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6907 ObjCMethodDecl *MD = Methods[i];
6908 std::string MethodTypeString, QuoteMethodTypeString;
6909 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString, true);
6910 RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString);
6911 Result += "\t\""; Result += QuoteMethodTypeString; Result += "\"";
6912 if (i == e-1)
6913 Result += "\n};\n";
6914 else {
6915 Result += ",\n";
6916 }
6917 }
6918}
6919
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00006920static void Write_IvarOffsetVar(RewriteModernObjC &RewriteObj,
6921 ASTContext *Context,
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00006922 std::string &Result,
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006923 ArrayRef<ObjCIvarDecl *> Ivars,
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006924 ObjCInterfaceDecl *CDecl) {
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006925 // FIXME. visibilty of offset symbols may have to be set; for Darwin
6926 // this is what happens:
6927 /**
6928 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
6929 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
6930 Class->getVisibility() == HiddenVisibility)
6931 Visibility shoud be: HiddenVisibility;
6932 else
6933 Visibility shoud be: DefaultVisibility;
6934 */
6935
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006936 Result += "\n";
6937 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6938 ObjCIvarDecl *IvarDecl = Ivars[i];
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00006939 if (Context->getLangOpts().MicrosoftExt)
6940 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
6941
6942 if (!Context->getLangOpts().MicrosoftExt ||
6943 IvarDecl->getAccessControl() == ObjCIvarDecl::Private ||
Fariborz Jahanian117591f2012-03-10 01:34:42 +00006944 IvarDecl->getAccessControl() == ObjCIvarDecl::Package)
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006945 Result += "extern \"C\" unsigned long int ";
Fariborz Jahaniand1c84d32012-03-10 00:53:02 +00006946 else
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006947 Result += "extern \"C\" __declspec(dllexport) unsigned long int ";
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00006948 if (Ivars[i]->isBitField())
6949 RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
6950 else
6951 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006952 Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))";
6953 Result += " = ";
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00006954 RewriteObj.RewriteIvarOffsetComputation(IvarDecl, Result);
6955 Result += ";\n";
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00006956 if (Ivars[i]->isBitField()) {
6957 // skip over rest of the ivar bitfields.
6958 SKIP_BITFIELDS(i , e, Ivars);
6959 }
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006960 }
6961}
6962
Fariborz Jahanianae932952012-02-10 20:47:10 +00006963static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj,
6964 ASTContext *Context, std::string &Result,
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00006965 ArrayRef<ObjCIvarDecl *> OriginalIvars,
Fariborz Jahanianae932952012-02-10 20:47:10 +00006966 StringRef VarName,
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006967 ObjCInterfaceDecl *CDecl) {
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00006968 if (OriginalIvars.size() > 0) {
6969 Write_IvarOffsetVar(RewriteObj, Context, Result, OriginalIvars, CDecl);
6970 SmallVector<ObjCIvarDecl *, 8> Ivars;
6971 // strip off all but the first ivar bitfield from each group of ivars.
6972 // Such ivars in the ivar list table will be replaced by their grouping struct
6973 // 'ivar'.
6974 for (unsigned i = 0, e = OriginalIvars.size(); i < e; i++) {
6975 if (OriginalIvars[i]->isBitField()) {
6976 Ivars.push_back(OriginalIvars[i]);
6977 // skip over rest of the ivar bitfields.
6978 SKIP_BITFIELDS(i , e, OriginalIvars);
6979 }
6980 else
6981 Ivars.push_back(OriginalIvars[i]);
6982 }
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006983
Fariborz Jahanianae932952012-02-10 20:47:10 +00006984 Result += "\nstatic ";
6985 Write__ivar_list_t_TypeDecl(Result, Ivars.size());
6986 Result += " "; Result += VarName;
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006987 Result += CDecl->getNameAsString();
Fariborz Jahanianae932952012-02-10 20:47:10 +00006988 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6989 Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n";
6990 Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n";
6991 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6992 ObjCIvarDecl *IvarDecl = Ivars[i];
6993 if (i == 0)
6994 Result += "\t{{";
6995 else
6996 Result += "\t {";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006997 Result += "(unsigned long int *)&";
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00006998 if (Ivars[i]->isBitField())
6999 RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
7000 else
7001 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahaniandb649232012-02-13 20:59:02 +00007002 Result += ", ";
Fariborz Jahanianae932952012-02-10 20:47:10 +00007003
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00007004 Result += "\"";
7005 if (Ivars[i]->isBitField())
7006 RewriteObj.ObjCIvarBitfieldGroupDecl(Ivars[i], Result);
7007 else
7008 Result += IvarDecl->getName();
7009 Result += "\", ";
7010
7011 QualType IVQT = IvarDecl->getType();
7012 if (IvarDecl->isBitField())
7013 IVQT = RewriteObj.GetGroupRecordTypeForObjCIvarBitfield(IvarDecl);
7014
Fariborz Jahanianae932952012-02-10 20:47:10 +00007015 std::string IvarTypeString, QuoteIvarTypeString;
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00007016 Context->getObjCEncodingForType(IVQT, IvarTypeString,
Fariborz Jahanianae932952012-02-10 20:47:10 +00007017 IvarDecl);
7018 RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString);
7019 Result += "\""; Result += QuoteIvarTypeString; Result += "\", ";
7020
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00007021 // FIXME. this alignment represents the host alignment and need be changed to
7022 // represent the target alignment.
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00007023 unsigned Align = Context->getTypeAlign(IVQT)/8;
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00007024 Align = llvm::Log2_32(Align);
Fariborz Jahanianae932952012-02-10 20:47:10 +00007025 Result += llvm::utostr(Align); Result += ", ";
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00007026 CharUnits Size = Context->getTypeSizeInChars(IVQT);
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00007027 Result += llvm::utostr(Size.getQuantity());
Fariborz Jahanianae932952012-02-10 20:47:10 +00007028 if (i == e-1)
7029 Result += "}}\n";
7030 else
7031 Result += "},\n";
7032 }
7033 Result += "};\n";
7034 }
7035}
7036
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007037/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00007038void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl,
7039 std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007040
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007041 // Do not synthesize the protocol more than once.
7042 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
7043 return;
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00007044 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007045
7046 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
7047 PDecl = Def;
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00007048 // Must write out all protocol definitions in current qualifier list,
7049 // and in their nested qualifiers before writing out current definition.
7050 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
7051 E = PDecl->protocol_end(); I != E; ++I)
7052 RewriteObjCProtocolMetaData(*I, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007053
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00007054 // Construct method lists.
7055 std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
7056 std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
7057 for (ObjCProtocolDecl::instmeth_iterator
7058 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
7059 I != E; ++I) {
7060 ObjCMethodDecl *MD = *I;
7061 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
7062 OptInstanceMethods.push_back(MD);
7063 } else {
7064 InstanceMethods.push_back(MD);
7065 }
7066 }
7067
7068 for (ObjCProtocolDecl::classmeth_iterator
7069 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
7070 I != E; ++I) {
7071 ObjCMethodDecl *MD = *I;
7072 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
7073 OptClassMethods.push_back(MD);
7074 } else {
7075 ClassMethods.push_back(MD);
7076 }
7077 }
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00007078 std::vector<ObjCMethodDecl *> AllMethods;
7079 for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++)
7080 AllMethods.push_back(InstanceMethods[i]);
7081 for (unsigned i = 0, e = ClassMethods.size(); i < e; i++)
7082 AllMethods.push_back(ClassMethods[i]);
7083 for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++)
7084 AllMethods.push_back(OptInstanceMethods[i]);
7085 for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++)
7086 AllMethods.push_back(OptClassMethods[i]);
7087
7088 Write__extendedMethodTypes_initializer(*this, Context, Result,
7089 AllMethods,
7090 "_OBJC_PROTOCOL_METHOD_TYPES_",
7091 PDecl->getNameAsString());
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00007092 // Protocol's super protocol list
7093 std::vector<ObjCProtocolDecl *> SuperProtocols;
7094 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
7095 E = PDecl->protocol_end(); I != E; ++I)
7096 SuperProtocols.push_back(*I);
7097
7098 Write_protocol_list_initializer(Context, Result, SuperProtocols,
7099 "_OBJC_PROTOCOL_REFS_",
7100 PDecl->getNameAsString());
7101
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007102 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00007103 "_OBJC_PROTOCOL_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007104 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00007105
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007106 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00007107 "_OBJC_PROTOCOL_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007108 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00007109
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007110 Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00007111 "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007112 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00007113
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007114 Write_method_list_t_initializer(*this, Context, Result, OptClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00007115 "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007116 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00007117
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00007118 // Protocol's property metadata.
7119 std::vector<ObjCPropertyDecl *> ProtocolProperties;
7120 for (ObjCContainerDecl::prop_iterator I = PDecl->prop_begin(),
7121 E = PDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00007122 ProtocolProperties.push_back(*I);
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00007123
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007124 Write_prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00007125 /* Container */0,
7126 "_OBJC_PROTOCOL_PROPERTIES_",
7127 PDecl->getNameAsString());
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00007128
Fariborz Jahanian82848c22012-02-08 00:50:52 +00007129 // Writer out root metadata for current protocol: struct _protocol_t
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007130 Result += "\n";
7131 if (LangOpts.MicrosoftExt)
Fariborz Jahanian8590d862012-04-14 17:13:08 +00007132 Result += "static ";
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00007133 Result += "struct _protocol_t _OBJC_PROTOCOL_";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007134 Result += PDecl->getNameAsString();
Fariborz Jahanian82848c22012-02-08 00:50:52 +00007135 Result += " __attribute__ ((used, section (\"__DATA,__datacoal_nt,coalesced\"))) = {\n";
7136 Result += "\t0,\n"; // id is; is null
7137 Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n";
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00007138 if (SuperProtocols.size() > 0) {
7139 Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_";
7140 Result += PDecl->getNameAsString(); Result += ",\n";
7141 }
7142 else
7143 Result += "\t0,\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00007144 if (InstanceMethods.size() > 0) {
7145 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
7146 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007147 }
7148 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00007149 Result += "\t0,\n";
7150
7151 if (ClassMethods.size() > 0) {
7152 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_";
7153 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007154 }
7155 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00007156 Result += "\t0,\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007157
Fariborz Jahanian82848c22012-02-08 00:50:52 +00007158 if (OptInstanceMethods.size() > 0) {
7159 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_";
7160 Result += PDecl->getNameAsString(); Result += ",\n";
7161 }
7162 else
7163 Result += "\t0,\n";
7164
7165 if (OptClassMethods.size() > 0) {
7166 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_";
7167 Result += PDecl->getNameAsString(); Result += ",\n";
7168 }
7169 else
7170 Result += "\t0,\n";
7171
7172 if (ProtocolProperties.size() > 0) {
7173 Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_";
7174 Result += PDecl->getNameAsString(); Result += ",\n";
7175 }
7176 else
7177 Result += "\t0,\n";
7178
7179 Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n";
7180 Result += "\t0,\n";
7181
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00007182 if (AllMethods.size() > 0) {
7183 Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_";
7184 Result += PDecl->getNameAsString();
7185 Result += "\n};\n";
7186 }
7187 else
7188 Result += "\t0\n};\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00007189
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00007190 if (LangOpts.MicrosoftExt)
Fariborz Jahanian8590d862012-04-14 17:13:08 +00007191 Result += "static ";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00007192 Result += "struct _protocol_t *";
7193 Result += "_OBJC_LABEL_PROTOCOL_$_"; Result += PDecl->getNameAsString();
7194 Result += " = &_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
7195 Result += ";\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00007196
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007197 // Mark this protocol as having been generated.
7198 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()))
7199 llvm_unreachable("protocol already synthesized");
7200
7201}
7202
7203void RewriteModernObjC::RewriteObjCProtocolListMetaData(
7204 const ObjCList<ObjCProtocolDecl> &Protocols,
7205 StringRef prefix, StringRef ClassName,
7206 std::string &Result) {
7207 if (Protocols.empty()) return;
7208
7209 for (unsigned i = 0; i != Protocols.size(); i++)
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00007210 RewriteObjCProtocolMetaData(Protocols[i], Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007211
7212 // Output the top lovel protocol meta-data for the class.
7213 /* struct _objc_protocol_list {
7214 struct _objc_protocol_list *next;
7215 int protocol_count;
7216 struct _objc_protocol *class_protocols[];
7217 }
7218 */
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007219 Result += "\n";
7220 if (LangOpts.MicrosoftExt)
7221 Result += "__declspec(allocate(\".cat_cls_meth$B\")) ";
7222 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007223 Result += "\tstruct _objc_protocol_list *next;\n";
7224 Result += "\tint protocol_count;\n";
7225 Result += "\tstruct _objc_protocol *class_protocols[";
7226 Result += utostr(Protocols.size());
7227 Result += "];\n} _OBJC_";
7228 Result += prefix;
7229 Result += "_PROTOCOLS_";
7230 Result += ClassName;
7231 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
7232 "{\n\t0, ";
7233 Result += utostr(Protocols.size());
7234 Result += "\n";
7235
7236 Result += "\t,{&_OBJC_PROTOCOL_";
7237 Result += Protocols[0]->getNameAsString();
7238 Result += " \n";
7239
7240 for (unsigned i = 1; i != Protocols.size(); i++) {
7241 Result += "\t ,&_OBJC_PROTOCOL_";
7242 Result += Protocols[i]->getNameAsString();
7243 Result += "\n";
7244 }
7245 Result += "\t }\n};\n";
7246}
7247
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00007248/// hasObjCExceptionAttribute - Return true if this class or any super
7249/// class has the __objc_exception__ attribute.
7250/// FIXME. Move this to ASTContext.cpp as it is also used for IRGen.
7251static bool hasObjCExceptionAttribute(ASTContext &Context,
7252 const ObjCInterfaceDecl *OID) {
7253 if (OID->hasAttr<ObjCExceptionAttr>())
7254 return true;
7255 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
7256 return hasObjCExceptionAttribute(Context, Super);
7257 return false;
7258}
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007259
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007260void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
7261 std::string &Result) {
7262 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7263
7264 // Explicitly declared @interface's are already synthesized.
Fariborz Jahanianae932952012-02-10 20:47:10 +00007265 if (CDecl->isImplicitInterfaceDecl())
7266 assert(false &&
7267 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00007268
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00007269 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanianae932952012-02-10 20:47:10 +00007270 SmallVector<ObjCIvarDecl *, 8> IVars;
7271
7272 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7273 IVD; IVD = IVD->getNextIvar()) {
7274 // Ignore unnamed bit-fields.
7275 if (!IVD->getDeclName())
7276 continue;
7277 IVars.push_back(IVD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007278 }
7279
Fariborz Jahanianae932952012-02-10 20:47:10 +00007280 Write__ivar_list_t_initializer(*this, Context, Result, IVars,
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007281 "_OBJC_$_INSTANCE_VARIABLES_",
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00007282 CDecl);
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007283
7284 // Build _objc_method_list for class's instance methods if needed
7285 SmallVector<ObjCMethodDecl *, 32>
7286 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
7287
7288 // If any of our property implementations have associated getters or
7289 // setters, produce metadata for them as well.
7290 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
7291 PropEnd = IDecl->propimpl_end();
7292 Prop != PropEnd; ++Prop) {
David Blaikie262bc182012-04-30 02:36:29 +00007293 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007294 continue;
David Blaikie262bc182012-04-30 02:36:29 +00007295 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007296 continue;
David Blaikie262bc182012-04-30 02:36:29 +00007297 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007298 if (!PD)
7299 continue;
7300 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
Fariborz Jahanian301e2e42012-05-03 22:52:13 +00007301 if (mustSynthesizeSetterGetterMethod(IDecl, PD, true /*getter*/))
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007302 InstanceMethods.push_back(Getter);
7303 if (PD->isReadOnly())
7304 continue;
7305 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
Fariborz Jahanian301e2e42012-05-03 22:52:13 +00007306 if (mustSynthesizeSetterGetterMethod(IDecl, PD, false /*setter*/))
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007307 InstanceMethods.push_back(Setter);
7308 }
7309
7310 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7311 "_OBJC_$_INSTANCE_METHODS_",
7312 IDecl->getNameAsString(), true);
7313
7314 SmallVector<ObjCMethodDecl *, 32>
7315 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
7316
7317 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7318 "_OBJC_$_CLASS_METHODS_",
7319 IDecl->getNameAsString(), true);
Fariborz Jahanian0a525342012-02-14 19:31:35 +00007320
7321 // Protocols referenced in class declaration?
7322 // Protocol's super protocol list
7323 std::vector<ObjCProtocolDecl *> RefedProtocols;
7324 const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols();
7325 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
7326 E = Protocols.end();
7327 I != E; ++I) {
7328 RefedProtocols.push_back(*I);
7329 // Must write out all protocol definitions in current qualifier list,
7330 // and in their nested qualifiers before writing out current definition.
7331 RewriteObjCProtocolMetaData(*I, Result);
7332 }
7333
7334 Write_protocol_list_initializer(Context, Result,
7335 RefedProtocols,
7336 "_OBJC_CLASS_PROTOCOLS_$_",
7337 IDecl->getNameAsString());
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007338
7339 // Protocol's property metadata.
7340 std::vector<ObjCPropertyDecl *> ClassProperties;
7341 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
7342 E = CDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00007343 ClassProperties.push_back(*I);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007344
7345 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahanian2df089d2012-03-22 17:39:35 +00007346 /* Container */IDecl,
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00007347 "_OBJC_$_PROP_LIST_",
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007348 CDecl->getNameAsString());
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007349
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007350
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00007351 // Data for initializing _class_ro_t metaclass meta-data
7352 uint32_t flags = CLS_META;
7353 std::string InstanceSize;
7354 std::string InstanceStart;
7355
7356
7357 bool classIsHidden = CDecl->getVisibility() == HiddenVisibility;
7358 if (classIsHidden)
7359 flags |= OBJC2_CLS_HIDDEN;
7360
7361 if (!CDecl->getSuperClass())
7362 // class is root
7363 flags |= CLS_ROOT;
7364 InstanceSize = "sizeof(struct _class_t)";
7365 InstanceStart = InstanceSize;
7366 Write__class_ro_t_initializer(Context, Result, flags,
7367 InstanceStart, InstanceSize,
7368 ClassMethods,
7369 0,
7370 0,
7371 0,
7372 "_OBJC_METACLASS_RO_$_",
7373 CDecl->getNameAsString());
7374
7375
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007376 // Data for initializing _class_ro_t meta-data
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00007377 flags = CLS;
7378 if (classIsHidden)
7379 flags |= OBJC2_CLS_HIDDEN;
7380
7381 if (hasObjCExceptionAttribute(*Context, CDecl))
7382 flags |= CLS_EXCEPTION;
7383
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007384 if (!CDecl->getSuperClass())
7385 // class is root
7386 flags |= CLS_ROOT;
7387
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00007388 InstanceSize.clear();
7389 InstanceStart.clear();
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007390 if (!ObjCSynthesizedStructs.count(CDecl)) {
7391 InstanceSize = "0";
7392 InstanceStart = "0";
7393 }
7394 else {
7395 InstanceSize = "sizeof(struct ";
7396 InstanceSize += CDecl->getNameAsString();
7397 InstanceSize += "_IMPL)";
7398
7399 ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7400 if (IVD) {
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00007401 RewriteIvarOffsetComputation(IVD, InstanceStart);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007402 }
7403 else
7404 InstanceStart = InstanceSize;
7405 }
7406 Write__class_ro_t_initializer(Context, Result, flags,
7407 InstanceStart, InstanceSize,
7408 InstanceMethods,
7409 RefedProtocols,
7410 IVars,
7411 ClassProperties,
7412 "_OBJC_CLASS_RO_$_",
7413 CDecl->getNameAsString());
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00007414
7415 Write_class_t(Context, Result,
7416 "OBJC_METACLASS_$_",
7417 CDecl, /*metaclass*/true);
7418
7419 Write_class_t(Context, Result,
7420 "OBJC_CLASS_$_",
7421 CDecl, /*metaclass*/false);
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007422
7423 if (ImplementationIsNonLazy(IDecl))
7424 DefinedNonLazyClasses.push_back(CDecl);
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00007425
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007426}
7427
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007428void RewriteModernObjC::RewriteClassSetupInitHook(std::string &Result) {
7429 int ClsDefCount = ClassImplementation.size();
7430 if (!ClsDefCount)
7431 return;
7432 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7433 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7434 Result += "static void *OBJC_CLASS_SETUP[] = {\n";
7435 for (int i = 0; i < ClsDefCount; i++) {
7436 ObjCImplementationDecl *IDecl = ClassImplementation[i];
7437 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7438 Result += "\t(void *)&OBJC_CLASS_SETUP_$_";
7439 Result += CDecl->getName(); Result += ",\n";
7440 }
7441 Result += "};\n";
7442}
7443
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007444void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
7445 int ClsDefCount = ClassImplementation.size();
7446 int CatDefCount = CategoryImplementation.size();
7447
7448 // For each implemented class, write out all its meta data.
7449 for (int i = 0; i < ClsDefCount; i++)
7450 RewriteObjCClassMetaData(ClassImplementation[i], Result);
7451
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007452 RewriteClassSetupInitHook(Result);
7453
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007454 // For each implemented category, write out all its meta data.
7455 for (int i = 0; i < CatDefCount; i++)
7456 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
7457
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007458 RewriteCategorySetupInitHook(Result);
7459
Fariborz Jahaniandf795672012-02-17 00:06:14 +00007460 if (ClsDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007461 if (LangOpts.MicrosoftExt)
7462 Result += "__declspec(allocate(\".objc_classlist$B\")) ";
Fariborz Jahaniandf795672012-02-17 00:06:14 +00007463 Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ [";
7464 Result += llvm::utostr(ClsDefCount); Result += "]";
7465 Result +=
7466 " __attribute__((used, section (\"__DATA, __objc_classlist,"
7467 "regular,no_dead_strip\")))= {\n";
7468 for (int i = 0; i < ClsDefCount; i++) {
7469 Result += "\t&OBJC_CLASS_$_";
7470 Result += ClassImplementation[i]->getNameAsString();
7471 Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007472 }
Fariborz Jahaniandf795672012-02-17 00:06:14 +00007473 Result += "};\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007474
7475 if (!DefinedNonLazyClasses.empty()) {
7476 if (LangOpts.MicrosoftExt)
7477 Result += "__declspec(allocate(\".objc_nlclslist$B\")) \n";
7478 Result += "static struct _class_t *_OBJC_LABEL_NONLAZY_CLASS_$[] = {\n\t";
7479 for (unsigned i = 0, e = DefinedNonLazyClasses.size(); i < e; i++) {
7480 Result += "\t&OBJC_CLASS_$_"; Result += DefinedNonLazyClasses[i]->getNameAsString();
7481 Result += ",\n";
7482 }
7483 Result += "};\n";
7484 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007485 }
Fariborz Jahanian61186122012-02-17 18:40:41 +00007486
7487 if (CatDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007488 if (LangOpts.MicrosoftExt)
7489 Result += "__declspec(allocate(\".objc_catlist$B\")) ";
Fariborz Jahanian61186122012-02-17 18:40:41 +00007490 Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [";
7491 Result += llvm::utostr(CatDefCount); Result += "]";
7492 Result +=
7493 " __attribute__((used, section (\"__DATA, __objc_catlist,"
7494 "regular,no_dead_strip\")))= {\n";
7495 for (int i = 0; i < CatDefCount; i++) {
7496 Result += "\t&_OBJC_$_CATEGORY_";
7497 Result +=
7498 CategoryImplementation[i]->getClassInterface()->getNameAsString();
7499 Result += "_$_";
7500 Result += CategoryImplementation[i]->getNameAsString();
7501 Result += ",\n";
7502 }
7503 Result += "};\n";
7504 }
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007505
7506 if (!DefinedNonLazyCategories.empty()) {
7507 if (LangOpts.MicrosoftExt)
7508 Result += "__declspec(allocate(\".objc_nlcatlist$B\")) \n";
7509 Result += "static struct _category_t *_OBJC_LABEL_NONLAZY_CATEGORY_$[] = {\n\t";
7510 for (unsigned i = 0, e = DefinedNonLazyCategories.size(); i < e; i++) {
7511 Result += "\t&_OBJC_$_CATEGORY_";
7512 Result +=
7513 DefinedNonLazyCategories[i]->getClassInterface()->getNameAsString();
7514 Result += "_$_";
7515 Result += DefinedNonLazyCategories[i]->getNameAsString();
7516 Result += ",\n";
7517 }
7518 Result += "};\n";
7519 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007520}
7521
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00007522void RewriteModernObjC::WriteImageInfo(std::string &Result) {
7523 if (LangOpts.MicrosoftExt)
7524 Result += "__declspec(allocate(\".objc_imageinfo$B\")) \n";
7525
7526 Result += "static struct IMAGE_INFO { unsigned version; unsigned flag; } ";
7527 // version 0, ObjCABI is 2
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00007528 Result += "_OBJC_IMAGE_INFO = { 0, 2 };\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00007529}
7530
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007531/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
7532/// implementation.
7533void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
7534 std::string &Result) {
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00007535 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007536 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7537 // Find category declaration for this implementation.
Douglas Gregord3297242013-01-16 23:00:23 +00007538 ObjCCategoryDecl *CDecl
7539 = ClassDecl->FindCategoryDeclaration(IDecl->getIdentifier());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007540
7541 std::string FullCategoryName = ClassDecl->getNameAsString();
Fariborz Jahanian61186122012-02-17 18:40:41 +00007542 FullCategoryName += "_$_";
7543 FullCategoryName += CDecl->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007544
7545 // Build _objc_method_list for class's instance methods if needed
7546 SmallVector<ObjCMethodDecl *, 32>
7547 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
7548
7549 // If any of our property implementations have associated getters or
7550 // setters, produce metadata for them as well.
7551 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
7552 PropEnd = IDecl->propimpl_end();
7553 Prop != PropEnd; ++Prop) {
David Blaikie262bc182012-04-30 02:36:29 +00007554 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007555 continue;
David Blaikie262bc182012-04-30 02:36:29 +00007556 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007557 continue;
David Blaikie262bc182012-04-30 02:36:29 +00007558 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007559 if (!PD)
7560 continue;
7561 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
7562 InstanceMethods.push_back(Getter);
7563 if (PD->isReadOnly())
7564 continue;
7565 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
7566 InstanceMethods.push_back(Setter);
7567 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007568
Fariborz Jahanian61186122012-02-17 18:40:41 +00007569 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7570 "_OBJC_$_CATEGORY_INSTANCE_METHODS_",
7571 FullCategoryName, true);
7572
7573 SmallVector<ObjCMethodDecl *, 32>
7574 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
7575
7576 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7577 "_OBJC_$_CATEGORY_CLASS_METHODS_",
7578 FullCategoryName, true);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007579
7580 // Protocols referenced in class declaration?
Fariborz Jahanian61186122012-02-17 18:40:41 +00007581 // Protocol's super protocol list
7582 std::vector<ObjCProtocolDecl *> RefedProtocols;
Argyrios Kyrtzidisa5f44412012-03-13 01:09:41 +00007583 for (ObjCInterfaceDecl::protocol_iterator I = CDecl->protocol_begin(),
7584 E = CDecl->protocol_end();
7585
7586 I != E; ++I) {
Fariborz Jahanian61186122012-02-17 18:40:41 +00007587 RefedProtocols.push_back(*I);
7588 // Must write out all protocol definitions in current qualifier list,
7589 // and in their nested qualifiers before writing out current definition.
7590 RewriteObjCProtocolMetaData(*I, Result);
7591 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007592
Fariborz Jahanian61186122012-02-17 18:40:41 +00007593 Write_protocol_list_initializer(Context, Result,
7594 RefedProtocols,
7595 "_OBJC_CATEGORY_PROTOCOLS_$_",
7596 FullCategoryName);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007597
Fariborz Jahanian61186122012-02-17 18:40:41 +00007598 // Protocol's property metadata.
7599 std::vector<ObjCPropertyDecl *> ClassProperties;
7600 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
7601 E = CDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00007602 ClassProperties.push_back(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007603
Fariborz Jahanian61186122012-02-17 18:40:41 +00007604 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahanianebfa2722012-05-03 23:19:33 +00007605 /* Container */IDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00007606 "_OBJC_$_PROP_LIST_",
7607 FullCategoryName);
7608
7609 Write_category_t(*this, Context, Result,
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007610 CDecl,
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007611 ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00007612 InstanceMethods,
7613 ClassMethods,
7614 RefedProtocols,
7615 ClassProperties);
7616
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007617 // Determine if this category is also "non-lazy".
7618 if (ImplementationIsNonLazy(IDecl))
7619 DefinedNonLazyCategories.push_back(CDecl);
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007620
7621}
7622
7623void RewriteModernObjC::RewriteCategorySetupInitHook(std::string &Result) {
7624 int CatDefCount = CategoryImplementation.size();
7625 if (!CatDefCount)
7626 return;
7627 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7628 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7629 Result += "static void *OBJC_CATEGORY_SETUP[] = {\n";
7630 for (int i = 0; i < CatDefCount; i++) {
7631 ObjCCategoryImplDecl *IDecl = CategoryImplementation[i];
7632 ObjCCategoryDecl *CatDecl= IDecl->getCategoryDecl();
7633 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7634 Result += "\t(void *)&OBJC_CATEGORY_SETUP_$_";
7635 Result += ClassDecl->getName();
7636 Result += "_$_";
7637 Result += CatDecl->getName();
7638 Result += ",\n";
7639 }
7640 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007641}
7642
7643// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
7644/// class methods.
7645template<typename MethodIterator>
7646void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
7647 MethodIterator MethodEnd,
7648 bool IsInstanceMethod,
7649 StringRef prefix,
7650 StringRef ClassName,
7651 std::string &Result) {
7652 if (MethodBegin == MethodEnd) return;
7653
7654 if (!objc_impl_method) {
7655 /* struct _objc_method {
7656 SEL _cmd;
7657 char *method_types;
7658 void *_imp;
7659 }
7660 */
7661 Result += "\nstruct _objc_method {\n";
7662 Result += "\tSEL _cmd;\n";
7663 Result += "\tchar *method_types;\n";
7664 Result += "\tvoid *_imp;\n";
7665 Result += "};\n";
7666
7667 objc_impl_method = true;
7668 }
7669
7670 // Build _objc_method_list for class's methods if needed
7671
7672 /* struct {
7673 struct _objc_method_list *next_method;
7674 int method_count;
7675 struct _objc_method method_list[];
7676 }
7677 */
7678 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007679 Result += "\n";
7680 if (LangOpts.MicrosoftExt) {
7681 if (IsInstanceMethod)
7682 Result += "__declspec(allocate(\".inst_meth$B\")) ";
7683 else
7684 Result += "__declspec(allocate(\".cls_meth$B\")) ";
7685 }
7686 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007687 Result += "\tstruct _objc_method_list *next_method;\n";
7688 Result += "\tint method_count;\n";
7689 Result += "\tstruct _objc_method method_list[";
7690 Result += utostr(NumMethods);
7691 Result += "];\n} _OBJC_";
7692 Result += prefix;
7693 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
7694 Result += "_METHODS_";
7695 Result += ClassName;
7696 Result += " __attribute__ ((used, section (\"__OBJC, __";
7697 Result += IsInstanceMethod ? "inst" : "cls";
7698 Result += "_meth\")))= ";
7699 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
7700
7701 Result += "\t,{{(SEL)\"";
7702 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7703 std::string MethodTypeString;
7704 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7705 Result += "\", \"";
7706 Result += MethodTypeString;
7707 Result += "\", (void *)";
7708 Result += MethodInternalNames[*MethodBegin];
7709 Result += "}\n";
7710 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
7711 Result += "\t ,{(SEL)\"";
7712 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7713 std::string MethodTypeString;
7714 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7715 Result += "\", \"";
7716 Result += MethodTypeString;
7717 Result += "\", (void *)";
7718 Result += MethodInternalNames[*MethodBegin];
7719 Result += "}\n";
7720 }
7721 Result += "\t }\n};\n";
7722}
7723
7724Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
7725 SourceRange OldRange = IV->getSourceRange();
7726 Expr *BaseExpr = IV->getBase();
7727
7728 // Rewrite the base, but without actually doing replaces.
7729 {
7730 DisableReplaceStmtScope S(*this);
7731 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
7732 IV->setBase(BaseExpr);
7733 }
7734
7735 ObjCIvarDecl *D = IV->getDecl();
7736
7737 Expr *Replacement = IV;
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007738
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007739 if (BaseExpr->getType()->isObjCObjectPointerType()) {
7740 const ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +00007741 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007742 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
7743 // lookup which class implements the instance variable.
7744 ObjCInterfaceDecl *clsDeclared = 0;
7745 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
7746 clsDeclared);
7747 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
7748
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007749 // Build name of symbol holding ivar offset.
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00007750 std::string IvarOffsetName;
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00007751 if (D->isBitField())
7752 ObjCIvarBitfieldGroupOffset(D, IvarOffsetName);
7753 else
7754 WriteInternalIvarName(clsDeclared, D, IvarOffsetName);
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00007755
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00007756 ReferencedIvars[clsDeclared].insert(D);
7757
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007758 // cast offset to "char *".
7759 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context,
7760 Context->getPointerType(Context->CharTy),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007761 CK_BitCast,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007762 BaseExpr);
7763 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
7764 SourceLocation(), &Context->Idents.get(IvarOffsetName),
Rafael Espindola8f187f62013-04-03 15:50:00 +00007765 Context->UnsignedLongTy, 0, SC_Extern);
John McCallf4b88a42012-03-10 09:33:50 +00007766 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false,
7767 Context->UnsignedLongTy, VK_LValue,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007768 SourceLocation());
7769 BinaryOperator *addExpr =
7770 new (Context) BinaryOperator(castExpr, DRE, BO_Add,
7771 Context->getPointerType(Context->CharTy),
Lang Hamesbe9af122012-10-02 04:45:10 +00007772 VK_RValue, OK_Ordinary, SourceLocation(), false);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007773 // Don't forget the parens to enforce the proper binding.
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007774 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(),
7775 SourceLocation(),
7776 addExpr);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00007777 QualType IvarT = D->getType();
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00007778 if (D->isBitField())
7779 IvarT = GetGroupRecordTypeForObjCIvarBitfield(D);
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007780
Fariborz Jahanianf5eac482012-05-02 17:34:59 +00007781 if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007782 RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00007783 RD = RD->getDefinition();
7784 if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007785 // decltype(((Foo_IMPL*)0)->bar) *
Fariborz Jahanianf5eac482012-05-02 17:34:59 +00007786 ObjCContainerDecl *CDecl =
7787 dyn_cast<ObjCContainerDecl>(D->getDeclContext());
7788 // ivar in class extensions requires special treatment.
7789 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
7790 CDecl = CatDecl->getClassInterface();
7791 std::string RecName = CDecl->getName();
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007792 RecName += "_IMPL";
7793 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
7794 SourceLocation(), SourceLocation(),
7795 &Context->Idents.get(RecName.c_str()));
7796 QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
7797 unsigned UnsignedIntSize =
7798 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
7799 Expr *Zero = IntegerLiteral::Create(*Context,
7800 llvm::APInt(UnsignedIntSize, 0),
7801 Context->UnsignedIntTy, SourceLocation());
7802 Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
7803 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
7804 Zero);
7805 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
7806 SourceLocation(),
7807 &Context->Idents.get(D->getNameAsString()),
7808 IvarT, 0,
7809 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00007810 ICIS_NoInit);
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007811 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
7812 FD->getType(), VK_LValue,
7813 OK_Ordinary);
7814 IvarT = Context->getDecltypeType(ME, ME->getType());
7815 }
7816 }
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00007817 convertObjCTypeToCStyleType(IvarT);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00007818 QualType castT = Context->getPointerType(IvarT);
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007819
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007820 castExpr = NoTypeInfoCStyleCastExpr(Context,
7821 castT,
7822 CK_BitCast,
7823 PE);
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007824
7825
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00007826 Expr *Exp = new (Context) UnaryOperator(castExpr, UO_Deref, IvarT,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007827 VK_LValue, OK_Ordinary,
7828 SourceLocation());
7829 PE = new (Context) ParenExpr(OldRange.getBegin(),
7830 OldRange.getEnd(),
7831 Exp);
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00007832
7833 if (D->isBitField()) {
7834 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
7835 SourceLocation(),
7836 &Context->Idents.get(D->getNameAsString()),
7837 D->getType(), 0,
7838 /*BitWidth=*/D->getBitWidth(),
7839 /*Mutable=*/true,
7840 ICIS_NoInit);
7841 MemberExpr *ME = new (Context) MemberExpr(PE, /*isArrow*/false, FD, SourceLocation(),
7842 FD->getType(), VK_LValue,
7843 OK_Ordinary);
7844 Replacement = ME;
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007845
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00007846 }
7847 else
7848 Replacement = PE;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007849 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007850
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007851 ReplaceStmtWithRange(IV, Replacement, OldRange);
7852 return Replacement;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007853}