blob: 19407bafd08bf4c3b6450737796a8e4432187d50 [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;
Benjamin Kramere5753592013-09-09 14:48:42 +0000106 FunctionDecl *SuperConstructorFunctionDecl;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000107 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);
Craig Topper6b9240e2013-07-05 19:34:19 +0000310 void RewriteForwardClassDecl(const SmallVectorImpl<Decl *> &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);
Craig Topper6b9240e2013-07-05 19:34:19 +0000328 void RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &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,
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +0000414 QualType returnType,
415 SmallVectorImpl<QualType> &ArgTypes,
416 SmallVectorImpl<Expr*> &MsgExprs,
417 ObjCMethodDecl *Method);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000418
419 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
420 SourceLocation StartLoc=SourceLocation(),
421 SourceLocation EndLoc=SourceLocation());
422
423 void SynthCountByEnumWithState(std::string &buf);
424 void SynthMsgSendFunctionDecl();
425 void SynthMsgSendSuperFunctionDecl();
426 void SynthMsgSendStretFunctionDecl();
427 void SynthMsgSendFpretFunctionDecl();
428 void SynthMsgSendSuperStretFunctionDecl();
429 void SynthGetClassFunctionDecl();
430 void SynthGetMetaClassFunctionDecl();
431 void SynthGetSuperClassFunctionDecl();
432 void SynthSelGetUidFunctionDecl();
Benjamin Kramere5753592013-09-09 14:48:42 +0000433 void SynthSuperConstructorFunctionDecl();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000434
435 // Rewriting metadata
436 template<typename MethodIterator>
437 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
438 MethodIterator MethodEnd,
439 bool IsInstanceMethod,
440 StringRef prefix,
441 StringRef ClassName,
442 std::string &Result);
Fariborz Jahanianda9624a2012-02-08 19:53:58 +0000443 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
444 std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000445 void RewriteObjCProtocolListMetaData(
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000446 const ObjCList<ObjCProtocolDecl> &Prots,
447 StringRef prefix, StringRef ClassName, std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000448 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000449 std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000450 void RewriteClassSetupInitHook(std::string &Result);
Fariborz Jahaniane0335782012-03-27 18:41:05 +0000451
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000452 void RewriteMetaDataIntoBuffer(std::string &Result);
453 void WriteImageInfo(std::string &Result);
454 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000455 std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000456 void RewriteCategorySetupInitHook(std::string &Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000457
458 // Rewriting ivar
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000459 void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000460 std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000461 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000462
463
464 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
465 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
466 StringRef funcName, std::string Tag);
467 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
468 StringRef funcName, std::string Tag);
469 std::string SynthesizeBlockImpl(BlockExpr *CE,
470 std::string Tag, std::string Desc);
471 std::string SynthesizeBlockDescriptor(std::string DescTag,
472 std::string ImplTag,
473 int i, StringRef funcName,
474 unsigned hasCopy);
475 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
476 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
477 StringRef FunName);
478 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
479 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
Craig Topper6b9240e2013-07-05 19:34:19 +0000480 const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000481
482 // Misc. helper routines.
483 QualType getProtocolType();
484 void WarnAboutReturnGotoStmts(Stmt *S);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000485 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
486 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
487 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
488
489 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
490 void CollectBlockDeclRefInfo(BlockExpr *Exp);
491 void GetBlockDeclRefExprs(Stmt *S);
Craig Topper6b9240e2013-07-05 19:34:19 +0000492 void GetInnerBlockDeclRefExprs(Stmt *S,
493 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000494 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
495
496 // We avoid calling Type::isBlockPointerType(), since it operates on the
497 // canonical type. We only care if the top-level type is a closure pointer.
498 bool isTopLevelBlockPointerType(QualType T) {
499 return isa<BlockPointerType>(T);
500 }
501
502 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
503 /// to a function pointer type and upon success, returns true; false
504 /// otherwise.
505 bool convertBlockPointerToFunctionPointer(QualType &T) {
506 if (isTopLevelBlockPointerType(T)) {
507 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
508 T = Context->getPointerType(BPT->getPointeeType());
509 return true;
510 }
511 return false;
512 }
513
Fariborz Jahanian164d6f82012-02-13 18:57:49 +0000514 bool convertObjCTypeToCStyleType(QualType &T);
515
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000516 bool needToScanForQualifiers(QualType T);
517 QualType getSuperStructType();
518 QualType getConstantStringStructType();
519 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
520 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
521
522 void convertToUnqualifiedObjCType(QualType &T) {
Fariborz Jahaniane35abe12012-04-06 22:29:36 +0000523 if (T->isObjCQualifiedIdType()) {
524 bool isConst = T.isConstQualified();
525 T = isConst ? Context->getObjCIdType().withConst()
526 : Context->getObjCIdType();
527 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000528 else if (T->isObjCQualifiedClassType())
529 T = Context->getObjCClassType();
530 else if (T->isObjCObjectPointerType() &&
531 T->getPointeeType()->isObjCQualifiedInterfaceType()) {
532 if (const ObjCObjectPointerType * OBJPT =
533 T->getAsObjCInterfacePointerType()) {
534 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
535 T = QualType(IFaceT, 0);
536 T = Context->getPointerType(T);
537 }
538 }
539 }
540
541 // FIXME: This predicate seems like it would be useful to add to ASTContext.
542 bool isObjCType(QualType T) {
543 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
544 return false;
545
546 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
547
548 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
549 OCT == Context->getCanonicalType(Context->getObjCClassType()))
550 return true;
551
552 if (const PointerType *PT = OCT->getAs<PointerType>()) {
553 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
554 PT->getPointeeType()->isObjCQualifiedIdType())
555 return true;
556 }
557 return false;
558 }
559 bool PointerTypeTakesAnyBlockArguments(QualType QT);
560 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
561 void GetExtentOfArgList(const char *Name, const char *&LParen,
562 const char *&RParen);
563
564 void QuoteDoublequotes(std::string &From, std::string &To) {
565 for (unsigned i = 0; i < From.length(); i++) {
566 if (From[i] == '"')
567 To += "\\\"";
568 else
569 To += From[i];
570 }
571 }
572
573 QualType getSimpleFunctionType(QualType result,
Jordan Rosebea522f2013-03-08 21:51:21 +0000574 ArrayRef<QualType> args,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000575 bool variadic = false) {
576 if (result == Context->getObjCInstanceType())
577 result = Context->getObjCIdType();
578 FunctionProtoType::ExtProtoInfo fpi;
579 fpi.Variadic = variadic;
Jordan Rosebea522f2013-03-08 21:51:21 +0000580 return Context->getFunctionType(result, args, fpi);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000581 }
582
583 // Helper function: create a CStyleCastExpr with trivial type source info.
584 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
585 CastKind Kind, Expr *E) {
586 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
587 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, 0, TInfo,
588 SourceLocation(), SourceLocation());
589 }
Fariborz Jahanian88f7f752012-03-14 23:18:19 +0000590
591 bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const {
592 IdentifierInfo* II = &Context->Idents.get("load");
593 Selector LoadSel = Context->Selectors.getSelector(0, &II);
594 return OD->getClassMethod(LoadSel) != 0;
595 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000596 };
597
598}
599
600void RewriteModernObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
601 NamedDecl *D) {
602 if (const FunctionProtoType *fproto
603 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
604 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
605 E = fproto->arg_type_end(); I && (I != E); ++I)
606 if (isTopLevelBlockPointerType(*I)) {
607 // All the args are checked/rewritten. Don't call twice!
608 RewriteBlockPointerDecl(D);
609 break;
610 }
611 }
612}
613
614void RewriteModernObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
615 const PointerType *PT = funcType->getAs<PointerType>();
616 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
617 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
618}
619
620static bool IsHeaderFile(const std::string &Filename) {
621 std::string::size_type DotPos = Filename.rfind('.');
622
623 if (DotPos == std::string::npos) {
624 // no file extension
625 return false;
626 }
627
628 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
629 // C header: .h
630 // C++ header: .hh or .H;
631 return Ext == "h" || Ext == "hh" || Ext == "H";
632}
633
634RewriteModernObjC::RewriteModernObjC(std::string inFile, raw_ostream* OS,
635 DiagnosticsEngine &D, const LangOptions &LOpts,
Fariborz Jahanianada71912013-02-08 00:27:34 +0000636 bool silenceMacroWarn,
637 bool LineInfo)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000638 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
Fariborz Jahanianada71912013-02-08 00:27:34 +0000639 SilenceRewriteMacroWarning(silenceMacroWarn), GenerateLineInfo(LineInfo) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000640 IsHeader = IsHeaderFile(inFile);
641 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
642 "rewriting sub-expression within a macro (may not be correct)");
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +0000643 // FIXME. This should be an error. But if block is not called, it is OK. And it
644 // may break including some headers.
645 GlobalBlockRewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
646 "rewriting block literal declared in global scope is not implemented");
647
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000648 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
649 DiagnosticsEngine::Warning,
650 "rewriter doesn't support user-specified control flow semantics "
651 "for @try/@finally (code may not execute properly)");
652}
653
654ASTConsumer *clang::CreateModernObjCRewriter(const std::string& InFile,
655 raw_ostream* OS,
656 DiagnosticsEngine &Diags,
657 const LangOptions &LOpts,
Fariborz Jahanianada71912013-02-08 00:27:34 +0000658 bool SilenceRewriteMacroWarning,
659 bool LineInfo) {
660 return new RewriteModernObjC(InFile, OS, Diags, LOpts,
661 SilenceRewriteMacroWarning, LineInfo);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000662}
663
664void RewriteModernObjC::InitializeCommon(ASTContext &context) {
665 Context = &context;
666 SM = &Context->getSourceManager();
667 TUDecl = Context->getTranslationUnitDecl();
668 MsgSendFunctionDecl = 0;
669 MsgSendSuperFunctionDecl = 0;
670 MsgSendStretFunctionDecl = 0;
671 MsgSendSuperStretFunctionDecl = 0;
672 MsgSendFpretFunctionDecl = 0;
673 GetClassFunctionDecl = 0;
674 GetMetaClassFunctionDecl = 0;
675 GetSuperClassFunctionDecl = 0;
676 SelGetUidFunctionDecl = 0;
677 CFStringFunctionDecl = 0;
678 ConstantStringClassReference = 0;
679 NSStringRecord = 0;
680 CurMethodDef = 0;
681 CurFunctionDef = 0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000682 GlobalVarDecl = 0;
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +0000683 GlobalConstructionExp = 0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000684 SuperStructDecl = 0;
685 ProtocolTypeDecl = 0;
686 ConstantStringDecl = 0;
687 BcLabelCount = 0;
Benjamin Kramere5753592013-09-09 14:48:42 +0000688 SuperConstructorFunctionDecl = 0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000689 NumObjCStringLiterals = 0;
690 PropParentMap = 0;
691 CurrentBody = 0;
692 DisableReplaceStmt = false;
693 objc_impl_method = false;
694
695 // Get the ID and start/end of the main file.
696 MainFileID = SM->getMainFileID();
697 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
698 MainFileStart = MainBuf->getBufferStart();
699 MainFileEnd = MainBuf->getBufferEnd();
700
David Blaikie4e4d0842012-03-11 07:00:24 +0000701 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000702}
703
704//===----------------------------------------------------------------------===//
705// Top Level Driver Code
706//===----------------------------------------------------------------------===//
707
708void RewriteModernObjC::HandleTopLevelSingleDecl(Decl *D) {
709 if (Diags.hasErrorOccurred())
710 return;
711
712 // Two cases: either the decl could be in the main file, or it could be in a
713 // #included file. If the former, rewrite it now. If the later, check to see
714 // if we rewrote the #include/#import.
715 SourceLocation Loc = D->getLocation();
716 Loc = SM->getExpansionLoc(Loc);
717
718 // If this is for a builtin, ignore it.
719 if (Loc.isInvalid()) return;
720
721 // Look for built-in declarations that we need to refer during the rewrite.
722 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
723 RewriteFunctionDecl(FD);
724 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
725 // declared in <Foundation/NSString.h>
726 if (FVD->getName() == "_NSConstantStringClassReference") {
727 ConstantStringClassReference = FVD;
728 return;
729 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000730 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
731 RewriteCategoryDecl(CD);
732 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
733 if (PD->isThisDeclarationADefinition())
734 RewriteProtocolDecl(PD);
735 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
Fariborz Jahanian8e86b2d2012-04-04 17:16:15 +0000736 // FIXME. This will not work in all situations and leaving it out
737 // is harmless.
738 // RewriteLinkageSpec(LSD);
739
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000740 // Recurse into linkage specifications
741 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
742 DIEnd = LSD->decls_end();
743 DI != DIEnd; ) {
744 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
745 if (!IFace->isThisDeclarationADefinition()) {
746 SmallVector<Decl *, 8> DG;
747 SourceLocation StartLoc = IFace->getLocStart();
748 do {
749 if (isa<ObjCInterfaceDecl>(*DI) &&
750 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
751 StartLoc == (*DI)->getLocStart())
752 DG.push_back(*DI);
753 else
754 break;
755
756 ++DI;
757 } while (DI != DIEnd);
758 RewriteForwardClassDecl(DG);
759 continue;
760 }
Fariborz Jahanianb3f904f2012-04-03 17:35:38 +0000761 else {
762 // Keep track of all interface declarations seen.
763 ObjCInterfacesSeen.push_back(IFace);
764 ++DI;
765 continue;
766 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000767 }
768
769 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
770 if (!Proto->isThisDeclarationADefinition()) {
771 SmallVector<Decl *, 8> DG;
772 SourceLocation StartLoc = Proto->getLocStart();
773 do {
774 if (isa<ObjCProtocolDecl>(*DI) &&
775 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
776 StartLoc == (*DI)->getLocStart())
777 DG.push_back(*DI);
778 else
779 break;
780
781 ++DI;
782 } while (DI != DIEnd);
783 RewriteForwardProtocolDecl(DG);
784 continue;
785 }
786 }
787
788 HandleTopLevelSingleDecl(*DI);
789 ++DI;
790 }
791 }
792 // If we have a decl in the main file, see if we should rewrite it.
Eli Friedman24146972013-08-22 00:27:10 +0000793 if (SM->isWrittenInMainFile(Loc))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000794 return HandleDeclInMainFile(D);
795}
796
797//===----------------------------------------------------------------------===//
798// Syntactic (non-AST) Rewriting Code
799//===----------------------------------------------------------------------===//
800
801void RewriteModernObjC::RewriteInclude() {
802 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
803 StringRef MainBuf = SM->getBufferData(MainFileID);
804 const char *MainBufStart = MainBuf.begin();
805 const char *MainBufEnd = MainBuf.end();
806 size_t ImportLen = strlen("import");
807
808 // Loop over the whole file, looking for includes.
809 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
810 if (*BufPtr == '#') {
811 if (++BufPtr == MainBufEnd)
812 return;
813 while (*BufPtr == ' ' || *BufPtr == '\t')
814 if (++BufPtr == MainBufEnd)
815 return;
816 if (!strncmp(BufPtr, "import", ImportLen)) {
817 // replace import with include
818 SourceLocation ImportLoc =
819 LocStart.getLocWithOffset(BufPtr-MainBufStart);
820 ReplaceText(ImportLoc, ImportLen, "include");
821 BufPtr += ImportLen;
822 }
823 }
824 }
825}
826
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +0000827static void WriteInternalIvarName(const ObjCInterfaceDecl *IDecl,
828 ObjCIvarDecl *IvarDecl, std::string &Result) {
829 Result += "OBJC_IVAR_$_";
830 Result += IDecl->getName();
831 Result += "$";
832 Result += IvarDecl->getName();
833}
834
835std::string
836RewriteModernObjC::getIvarAccessString(ObjCIvarDecl *D) {
837 const ObjCInterfaceDecl *ClassDecl = D->getContainingInterface();
838
839 // Build name of symbol holding ivar offset.
840 std::string IvarOffsetName;
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +0000841 if (D->isBitField())
842 ObjCIvarBitfieldGroupOffset(D, IvarOffsetName);
843 else
844 WriteInternalIvarName(ClassDecl, D, IvarOffsetName);
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +0000845
846
847 std::string S = "(*(";
848 QualType IvarT = D->getType();
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +0000849 if (D->isBitField())
850 IvarT = GetGroupRecordTypeForObjCIvarBitfield(D);
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +0000851
852 if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
853 RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
854 RD = RD->getDefinition();
855 if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
856 // decltype(((Foo_IMPL*)0)->bar) *
857 ObjCContainerDecl *CDecl =
858 dyn_cast<ObjCContainerDecl>(D->getDeclContext());
859 // ivar in class extensions requires special treatment.
860 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
861 CDecl = CatDecl->getClassInterface();
862 std::string RecName = CDecl->getName();
863 RecName += "_IMPL";
864 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
865 SourceLocation(), SourceLocation(),
866 &Context->Idents.get(RecName.c_str()));
867 QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
868 unsigned UnsignedIntSize =
869 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
870 Expr *Zero = IntegerLiteral::Create(*Context,
871 llvm::APInt(UnsignedIntSize, 0),
872 Context->UnsignedIntTy, SourceLocation());
873 Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
874 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
875 Zero);
876 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
877 SourceLocation(),
878 &Context->Idents.get(D->getNameAsString()),
879 IvarT, 0,
880 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +0000881 ICIS_NoInit);
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +0000882 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
883 FD->getType(), VK_LValue,
884 OK_Ordinary);
885 IvarT = Context->getDecltypeType(ME, ME->getType());
886 }
887 }
888 convertObjCTypeToCStyleType(IvarT);
889 QualType castT = Context->getPointerType(IvarT);
890 std::string TypeString(castT.getAsString(Context->getPrintingPolicy()));
891 S += TypeString;
892 S += ")";
893
894 // ((char *)self + IVAR_OFFSET_SYMBOL_NAME)
895 S += "((char *)self + ";
896 S += IvarOffsetName;
897 S += "))";
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +0000898 if (D->isBitField()) {
899 S += ".";
900 S += D->getNameAsString();
901 }
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +0000902 ReferencedIvars[const_cast<ObjCInterfaceDecl *>(ClassDecl)].insert(D);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000903 return S;
904}
905
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000906/// mustSynthesizeSetterGetterMethod - returns true if setter or getter has not
907/// been found in the class implementation. In this case, it must be synthesized.
908static bool mustSynthesizeSetterGetterMethod(ObjCImplementationDecl *IMP,
909 ObjCPropertyDecl *PD,
910 bool getter) {
911 return getter ? !IMP->getInstanceMethod(PD->getGetterName())
912 : !IMP->getInstanceMethod(PD->getSetterName());
913
914}
915
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000916void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
917 ObjCImplementationDecl *IMD,
918 ObjCCategoryImplDecl *CID) {
919 static bool objcGetPropertyDefined = false;
920 static bool objcSetPropertyDefined = false;
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000921 SourceLocation startGetterSetterLoc;
922
923 if (PID->getLocStart().isValid()) {
924 SourceLocation startLoc = PID->getLocStart();
925 InsertText(startLoc, "// ");
926 const char *startBuf = SM->getCharacterData(startLoc);
927 assert((*startBuf == '@') && "bogus @synthesize location");
928 const char *semiBuf = strchr(startBuf, ';');
929 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
930 startGetterSetterLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
931 }
932 else
933 startGetterSetterLoc = IMD ? IMD->getLocEnd() : CID->getLocEnd();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000934
935 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
936 return; // FIXME: is this correct?
937
938 // Generate the 'getter' function.
939 ObjCPropertyDecl *PD = PID->getPropertyDecl();
940 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Jordan Rose62bbe072013-03-15 21:41:35 +0000941 assert(IMD && OID && "Synthesized ivars must be attached to @implementation");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000942
Bill Wendlingad017fa2012-12-20 19:22:21 +0000943 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000944 if (mustSynthesizeSetterGetterMethod(IMD, PD, true /*getter*/)) {
Bill Wendlingad017fa2012-12-20 19:22:21 +0000945 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
946 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000947 ObjCPropertyDecl::OBJC_PR_copy));
948 std::string Getr;
949 if (GenGetProperty && !objcGetPropertyDefined) {
950 objcGetPropertyDefined = true;
951 // FIXME. Is this attribute correct in all cases?
952 Getr = "\nextern \"C\" __declspec(dllimport) "
953 "id objc_getProperty(id, SEL, long, bool);\n";
954 }
955 RewriteObjCMethodDecl(OID->getContainingInterface(),
956 PD->getGetterMethodDecl(), Getr);
957 Getr += "{ ";
958 // Synthesize an explicit cast to gain access to the ivar.
959 // See objc-act.c:objc_synthesize_new_getter() for details.
960 if (GenGetProperty) {
961 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
962 Getr += "typedef ";
963 const FunctionType *FPRetType = 0;
964 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
965 FPRetType);
966 Getr += " _TYPE";
967 if (FPRetType) {
968 Getr += ")"; // close the precedence "scope" for "*".
969
970 // Now, emit the argument types (if any).
971 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
972 Getr += "(";
973 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
974 if (i) Getr += ", ";
975 std::string ParamStr = FT->getArgType(i).getAsString(
976 Context->getPrintingPolicy());
977 Getr += ParamStr;
978 }
979 if (FT->isVariadic()) {
980 if (FT->getNumArgs()) Getr += ", ";
981 Getr += "...";
982 }
983 Getr += ")";
984 } else
985 Getr += "()";
986 }
987 Getr += ";\n";
988 Getr += "return (_TYPE)";
989 Getr += "objc_getProperty(self, _cmd, ";
990 RewriteIvarOffsetComputation(OID, Getr);
991 Getr += ", 1)";
992 }
993 else
994 Getr += "return " + getIvarAccessString(OID);
995 Getr += "; }";
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000996 InsertText(startGetterSetterLoc, Getr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000997 }
998
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000999 if (PD->isReadOnly() ||
1000 !mustSynthesizeSetterGetterMethod(IMD, PD, false /*setter*/))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001001 return;
1002
1003 // Generate the 'setter' function.
1004 std::string Setr;
Bill Wendlingad017fa2012-12-20 19:22:21 +00001005 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001006 ObjCPropertyDecl::OBJC_PR_copy);
1007 if (GenSetProperty && !objcSetPropertyDefined) {
1008 objcSetPropertyDefined = true;
1009 // FIXME. Is this attribute correct in all cases?
1010 Setr = "\nextern \"C\" __declspec(dllimport) "
1011 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
1012 }
1013
1014 RewriteObjCMethodDecl(OID->getContainingInterface(),
1015 PD->getSetterMethodDecl(), Setr);
1016 Setr += "{ ";
1017 // Synthesize an explicit cast to initialize the ivar.
1018 // See objc-act.c:objc_synthesize_new_setter() for details.
1019 if (GenSetProperty) {
1020 Setr += "objc_setProperty (self, _cmd, ";
1021 RewriteIvarOffsetComputation(OID, Setr);
1022 Setr += ", (id)";
1023 Setr += PD->getName();
1024 Setr += ", ";
Bill Wendlingad017fa2012-12-20 19:22:21 +00001025 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001026 Setr += "0, ";
1027 else
1028 Setr += "1, ";
Bill Wendlingad017fa2012-12-20 19:22:21 +00001029 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001030 Setr += "1)";
1031 else
1032 Setr += "0)";
1033 }
1034 else {
1035 Setr += getIvarAccessString(OID) + " = ";
1036 Setr += PD->getName();
1037 }
Fariborz Jahanian301e2e42012-05-03 22:52:13 +00001038 Setr += "; }\n";
1039 InsertText(startGetterSetterLoc, Setr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001040}
1041
1042static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
1043 std::string &typedefString) {
Fariborz Jahanianbfaa1112013-02-08 17:15:07 +00001044 typedefString += "\n#ifndef _REWRITER_typedef_";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001045 typedefString += ForwardDecl->getNameAsString();
1046 typedefString += "\n";
1047 typedefString += "#define _REWRITER_typedef_";
1048 typedefString += ForwardDecl->getNameAsString();
1049 typedefString += "\n";
1050 typedefString += "typedef struct objc_object ";
1051 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001052 // typedef struct { } _objc_exc_Classname;
1053 typedefString += ";\ntypedef struct {} _objc_exc_";
1054 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001055 typedefString += ";\n#endif\n";
1056}
1057
1058void RewriteModernObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
1059 const std::string &typedefString) {
1060 SourceLocation startLoc = ClassDecl->getLocStart();
1061 const char *startBuf = SM->getCharacterData(startLoc);
1062 const char *semiPtr = strchr(startBuf, ';');
1063 // Replace the @class with typedefs corresponding to the classes.
1064 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
1065}
1066
1067void RewriteModernObjC::RewriteForwardClassDecl(DeclGroupRef D) {
1068 std::string typedefString;
1069 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
1070 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(*I);
1071 if (I == D.begin()) {
1072 // Translate to typedef's that forward reference structs with the same name
1073 // as the class. As a convenience, we include the original declaration
1074 // as a comment.
1075 typedefString += "// @class ";
1076 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanianbfaa1112013-02-08 17:15:07 +00001077 typedefString += ";";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001078 }
1079 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
1080 }
1081 DeclGroupRef::iterator I = D.begin();
1082 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
1083}
1084
1085void RewriteModernObjC::RewriteForwardClassDecl(
Craig Topper6b9240e2013-07-05 19:34:19 +00001086 const SmallVectorImpl<Decl *> &D) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001087 std::string typedefString;
1088 for (unsigned i = 0; i < D.size(); i++) {
1089 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
1090 if (i == 0) {
1091 typedefString += "// @class ";
1092 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanianbfaa1112013-02-08 17:15:07 +00001093 typedefString += ";";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001094 }
1095 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
1096 }
1097 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
1098}
1099
1100void RewriteModernObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
1101 // When method is a synthesized one, such as a getter/setter there is
1102 // nothing to rewrite.
1103 if (Method->isImplicit())
1104 return;
1105 SourceLocation LocStart = Method->getLocStart();
1106 SourceLocation LocEnd = Method->getLocEnd();
1107
1108 if (SM->getExpansionLineNumber(LocEnd) >
1109 SM->getExpansionLineNumber(LocStart)) {
1110 InsertText(LocStart, "#if 0\n");
1111 ReplaceText(LocEnd, 1, ";\n#endif\n");
1112 } else {
1113 InsertText(LocStart, "// ");
1114 }
1115}
1116
1117void RewriteModernObjC::RewriteProperty(ObjCPropertyDecl *prop) {
1118 SourceLocation Loc = prop->getAtLoc();
1119
1120 ReplaceText(Loc, 0, "// ");
1121 // FIXME: handle properties that are declared across multiple lines.
1122}
1123
1124void RewriteModernObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
1125 SourceLocation LocStart = CatDecl->getLocStart();
1126
1127 // FIXME: handle category headers that are declared across multiple lines.
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00001128 if (CatDecl->getIvarRBraceLoc().isValid()) {
1129 ReplaceText(LocStart, 1, "/** ");
1130 ReplaceText(CatDecl->getIvarRBraceLoc(), 1, "**/ ");
1131 }
1132 else {
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001133 ReplaceText(LocStart, 0, "// ");
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00001134 }
Fariborz Jahanianaf300292012-02-20 20:09:20 +00001135
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001136 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
1137 E = CatDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001138 RewriteProperty(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001139
1140 for (ObjCCategoryDecl::instmeth_iterator
1141 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
1142 I != E; ++I)
1143 RewriteMethodDeclaration(*I);
1144 for (ObjCCategoryDecl::classmeth_iterator
1145 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
1146 I != E; ++I)
1147 RewriteMethodDeclaration(*I);
1148
1149 // Lastly, comment out the @end.
1150 ReplaceText(CatDecl->getAtEndRange().getBegin(),
Fariborz Jahanianf9f30792013-04-03 19:11:21 +00001151 strlen("@end"), "/* @end */\n");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001152}
1153
1154void RewriteModernObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
1155 SourceLocation LocStart = PDecl->getLocStart();
1156 assert(PDecl->isThisDeclarationADefinition());
1157
1158 // FIXME: handle protocol headers that are declared across multiple lines.
1159 ReplaceText(LocStart, 0, "// ");
1160
1161 for (ObjCProtocolDecl::instmeth_iterator
1162 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
1163 I != E; ++I)
1164 RewriteMethodDeclaration(*I);
1165 for (ObjCProtocolDecl::classmeth_iterator
1166 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
1167 I != E; ++I)
1168 RewriteMethodDeclaration(*I);
1169
1170 for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
1171 E = PDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001172 RewriteProperty(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001173
1174 // Lastly, comment out the @end.
1175 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Fariborz Jahanianf9f30792013-04-03 19:11:21 +00001176 ReplaceText(LocEnd, strlen("@end"), "/* @end */\n");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001177
1178 // Must comment out @optional/@required
1179 const char *startBuf = SM->getCharacterData(LocStart);
1180 const char *endBuf = SM->getCharacterData(LocEnd);
1181 for (const char *p = startBuf; p < endBuf; p++) {
1182 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
1183 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1184 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
1185
1186 }
1187 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
1188 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1189 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
1190
1191 }
1192 }
1193}
1194
1195void RewriteModernObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1196 SourceLocation LocStart = (*D.begin())->getLocStart();
1197 if (LocStart.isInvalid())
1198 llvm_unreachable("Invalid SourceLocation");
1199 // FIXME: handle forward protocol that are declared across multiple lines.
1200 ReplaceText(LocStart, 0, "// ");
1201}
1202
1203void
Craig Topper6b9240e2013-07-05 19:34:19 +00001204RewriteModernObjC::RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001205 SourceLocation LocStart = DG[0]->getLocStart();
1206 if (LocStart.isInvalid())
1207 llvm_unreachable("Invalid SourceLocation");
1208 // FIXME: handle forward protocol that are declared across multiple lines.
1209 ReplaceText(LocStart, 0, "// ");
1210}
1211
Fariborz Jahanianb3f904f2012-04-03 17:35:38 +00001212void
1213RewriteModernObjC::RewriteLinkageSpec(LinkageSpecDecl *LSD) {
1214 SourceLocation LocStart = LSD->getExternLoc();
1215 if (LocStart.isInvalid())
1216 llvm_unreachable("Invalid extern SourceLocation");
1217
1218 ReplaceText(LocStart, 0, "// ");
1219 if (!LSD->hasBraces())
1220 return;
1221 // FIXME. We don't rewrite well if '{' is not on same line as 'extern'.
1222 SourceLocation LocRBrace = LSD->getRBraceLoc();
1223 if (LocRBrace.isInvalid())
1224 llvm_unreachable("Invalid rbrace SourceLocation");
1225 ReplaceText(LocRBrace, 0, "// ");
1226}
1227
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001228void RewriteModernObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1229 const FunctionType *&FPRetType) {
1230 if (T->isObjCQualifiedIdType())
1231 ResultStr += "id";
1232 else if (T->isFunctionPointerType() ||
1233 T->isBlockPointerType()) {
1234 // needs special handling, since pointer-to-functions have special
1235 // syntax (where a decaration models use).
1236 QualType retType = T;
1237 QualType PointeeTy;
1238 if (const PointerType* PT = retType->getAs<PointerType>())
1239 PointeeTy = PT->getPointeeType();
1240 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
1241 PointeeTy = BPT->getPointeeType();
1242 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
1243 ResultStr += FPRetType->getResultType().getAsString(
1244 Context->getPrintingPolicy());
1245 ResultStr += "(*";
1246 }
1247 } else
1248 ResultStr += T.getAsString(Context->getPrintingPolicy());
1249}
1250
1251void RewriteModernObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1252 ObjCMethodDecl *OMD,
1253 std::string &ResultStr) {
1254 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1255 const FunctionType *FPRetType = 0;
1256 ResultStr += "\nstatic ";
1257 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
1258 ResultStr += " ";
1259
1260 // Unique method name
1261 std::string NameStr;
1262
1263 if (OMD->isInstanceMethod())
1264 NameStr += "_I_";
1265 else
1266 NameStr += "_C_";
1267
1268 NameStr += IDecl->getNameAsString();
1269 NameStr += "_";
1270
1271 if (ObjCCategoryImplDecl *CID =
1272 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
1273 NameStr += CID->getNameAsString();
1274 NameStr += "_";
1275 }
1276 // Append selector names, replacing ':' with '_'
1277 {
1278 std::string selString = OMD->getSelector().getAsString();
1279 int len = selString.size();
1280 for (int i = 0; i < len; i++)
1281 if (selString[i] == ':')
1282 selString[i] = '_';
1283 NameStr += selString;
1284 }
1285 // Remember this name for metadata emission
1286 MethodInternalNames[OMD] = NameStr;
1287 ResultStr += NameStr;
1288
1289 // Rewrite arguments
1290 ResultStr += "(";
1291
1292 // invisible arguments
1293 if (OMD->isInstanceMethod()) {
1294 QualType selfTy = Context->getObjCInterfaceType(IDecl);
1295 selfTy = Context->getPointerType(selfTy);
1296 if (!LangOpts.MicrosoftExt) {
1297 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
1298 ResultStr += "struct ";
1299 }
1300 // When rewriting for Microsoft, explicitly omit the structure name.
1301 ResultStr += IDecl->getNameAsString();
1302 ResultStr += " *";
1303 }
1304 else
1305 ResultStr += Context->getObjCClassType().getAsString(
1306 Context->getPrintingPolicy());
1307
1308 ResultStr += " self, ";
1309 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
1310 ResultStr += " _cmd";
1311
1312 // Method arguments.
1313 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1314 E = OMD->param_end(); PI != E; ++PI) {
1315 ParmVarDecl *PDecl = *PI;
1316 ResultStr += ", ";
1317 if (PDecl->getType()->isObjCQualifiedIdType()) {
1318 ResultStr += "id ";
1319 ResultStr += PDecl->getNameAsString();
1320 } else {
1321 std::string Name = PDecl->getNameAsString();
1322 QualType QT = PDecl->getType();
1323 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian2610f902012-03-27 16:42:20 +00001324 (void)convertBlockPointerToFunctionPointer(QT);
1325 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001326 ResultStr += Name;
1327 }
1328 }
1329 if (OMD->isVariadic())
1330 ResultStr += ", ...";
1331 ResultStr += ") ";
1332
1333 if (FPRetType) {
1334 ResultStr += ")"; // close the precedence "scope" for "*".
1335
1336 // Now, emit the argument types (if any).
1337 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
1338 ResultStr += "(";
1339 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1340 if (i) ResultStr += ", ";
1341 std::string ParamStr = FT->getArgType(i).getAsString(
1342 Context->getPrintingPolicy());
1343 ResultStr += ParamStr;
1344 }
1345 if (FT->isVariadic()) {
1346 if (FT->getNumArgs()) ResultStr += ", ";
1347 ResultStr += "...";
1348 }
1349 ResultStr += ")";
1350 } else {
1351 ResultStr += "()";
1352 }
1353 }
1354}
1355void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) {
1356 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1357 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
1358
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001359 if (IMD) {
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00001360 if (IMD->getIvarRBraceLoc().isValid()) {
1361 ReplaceText(IMD->getLocStart(), 1, "/** ");
1362 ReplaceText(IMD->getIvarRBraceLoc(), 1, "**/ ");
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001363 }
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00001364 else {
1365 InsertText(IMD->getLocStart(), "// ");
1366 }
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001367 }
1368 else
1369 InsertText(CID->getLocStart(), "// ");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001370
1371 for (ObjCCategoryImplDecl::instmeth_iterator
1372 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1373 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
1374 I != E; ++I) {
1375 std::string ResultStr;
1376 ObjCMethodDecl *OMD = *I;
1377 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1378 SourceLocation LocStart = OMD->getLocStart();
1379 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1380
1381 const char *startBuf = SM->getCharacterData(LocStart);
1382 const char *endBuf = SM->getCharacterData(LocEnd);
1383 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1384 }
1385
1386 for (ObjCCategoryImplDecl::classmeth_iterator
1387 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1388 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
1389 I != E; ++I) {
1390 std::string ResultStr;
1391 ObjCMethodDecl *OMD = *I;
1392 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1393 SourceLocation LocStart = OMD->getLocStart();
1394 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1395
1396 const char *startBuf = SM->getCharacterData(LocStart);
1397 const char *endBuf = SM->getCharacterData(LocEnd);
1398 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1399 }
1400 for (ObjCCategoryImplDecl::propimpl_iterator
1401 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
1402 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
1403 I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00001404 RewritePropertyImplDecl(*I, IMD, CID);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001405 }
1406
1407 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
1408}
1409
1410void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00001411 // Do not synthesize more than once.
1412 if (ObjCSynthesizedStructs.count(ClassDecl))
1413 return;
1414 // Make sure super class's are written before current class is written.
1415 ObjCInterfaceDecl *SuperClass = ClassDecl->getSuperClass();
1416 while (SuperClass) {
1417 RewriteInterfaceDecl(SuperClass);
1418 SuperClass = SuperClass->getSuperClass();
1419 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001420 std::string ResultStr;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00001421 if (!ObjCWrittenInterfaces.count(ClassDecl->getCanonicalDecl())) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001422 // we haven't seen a forward decl - generate a typedef.
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001423 RewriteOneForwardClassDecl(ClassDecl, ResultStr);
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00001424 RewriteIvarOffsetSymbols(ClassDecl, ResultStr);
1425
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001426 RewriteObjCInternalStruct(ClassDecl, ResultStr);
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00001427 // Mark this typedef as having been written into its c++ equivalent.
1428 ObjCWrittenInterfaces.insert(ClassDecl->getCanonicalDecl());
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001429
1430 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001431 E = ClassDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001432 RewriteProperty(*I);
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001433 for (ObjCInterfaceDecl::instmeth_iterator
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001434 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001435 I != E; ++I)
1436 RewriteMethodDeclaration(*I);
1437 for (ObjCInterfaceDecl::classmeth_iterator
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001438 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001439 I != E; ++I)
1440 RewriteMethodDeclaration(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001441
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001442 // Lastly, comment out the @end.
1443 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
Fariborz Jahanianf9f30792013-04-03 19:11:21 +00001444 "/* @end */\n");
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001445 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001446}
1447
1448Stmt *RewriteModernObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1449 SourceRange OldRange = PseudoOp->getSourceRange();
1450
1451 // We just magically know some things about the structure of this
1452 // expression.
1453 ObjCMessageExpr *OldMsg =
1454 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1455 PseudoOp->getNumSemanticExprs() - 1));
1456
1457 // Because the rewriter doesn't allow us to rewrite rewritten code,
1458 // we need to suppress rewriting the sub-statements.
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001459 Expr *Base;
1460 SmallVector<Expr*, 2> Args;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001461 {
1462 DisableReplaceStmtScope S(*this);
1463
1464 // Rebuild the base expression if we have one.
1465 Base = 0;
1466 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1467 Base = OldMsg->getInstanceReceiver();
1468 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1469 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1470 }
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001471
1472 unsigned numArgs = OldMsg->getNumArgs();
1473 for (unsigned i = 0; i < numArgs; i++) {
1474 Expr *Arg = OldMsg->getArg(i);
1475 if (isa<OpaqueValueExpr>(Arg))
1476 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1477 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1478 Args.push_back(Arg);
1479 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001480 }
1481
1482 // TODO: avoid this copy.
1483 SmallVector<SourceLocation, 1> SelLocs;
1484 OldMsg->getSelectorLocs(SelLocs);
1485
1486 ObjCMessageExpr *NewMsg = 0;
1487 switch (OldMsg->getReceiverKind()) {
1488 case ObjCMessageExpr::Class:
1489 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1490 OldMsg->getValueKind(),
1491 OldMsg->getLeftLoc(),
1492 OldMsg->getClassReceiverTypeInfo(),
1493 OldMsg->getSelector(),
1494 SelLocs,
1495 OldMsg->getMethodDecl(),
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001496 Args,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001497 OldMsg->getRightLoc(),
1498 OldMsg->isImplicit());
1499 break;
1500
1501 case ObjCMessageExpr::Instance:
1502 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1503 OldMsg->getValueKind(),
1504 OldMsg->getLeftLoc(),
1505 Base,
1506 OldMsg->getSelector(),
1507 SelLocs,
1508 OldMsg->getMethodDecl(),
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001509 Args,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001510 OldMsg->getRightLoc(),
1511 OldMsg->isImplicit());
1512 break;
1513
1514 case ObjCMessageExpr::SuperClass:
1515 case ObjCMessageExpr::SuperInstance:
1516 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1517 OldMsg->getValueKind(),
1518 OldMsg->getLeftLoc(),
1519 OldMsg->getSuperLoc(),
1520 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1521 OldMsg->getSuperType(),
1522 OldMsg->getSelector(),
1523 SelLocs,
1524 OldMsg->getMethodDecl(),
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001525 Args,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001526 OldMsg->getRightLoc(),
1527 OldMsg->isImplicit());
1528 break;
1529 }
1530
1531 Stmt *Replacement = SynthMessageExpr(NewMsg);
1532 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1533 return Replacement;
1534}
1535
1536Stmt *RewriteModernObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1537 SourceRange OldRange = PseudoOp->getSourceRange();
1538
1539 // We just magically know some things about the structure of this
1540 // expression.
1541 ObjCMessageExpr *OldMsg =
1542 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1543
1544 // Because the rewriter doesn't allow us to rewrite rewritten code,
1545 // we need to suppress rewriting the sub-statements.
1546 Expr *Base = 0;
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001547 SmallVector<Expr*, 1> Args;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001548 {
1549 DisableReplaceStmtScope S(*this);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001550 // Rebuild the base expression if we have one.
1551 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1552 Base = OldMsg->getInstanceReceiver();
1553 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1554 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1555 }
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001556 unsigned numArgs = OldMsg->getNumArgs();
1557 for (unsigned i = 0; i < numArgs; i++) {
1558 Expr *Arg = OldMsg->getArg(i);
1559 if (isa<OpaqueValueExpr>(Arg))
1560 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1561 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1562 Args.push_back(Arg);
1563 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001564 }
1565
1566 // Intentionally empty.
1567 SmallVector<SourceLocation, 1> SelLocs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001568
1569 ObjCMessageExpr *NewMsg = 0;
1570 switch (OldMsg->getReceiverKind()) {
1571 case ObjCMessageExpr::Class:
1572 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1573 OldMsg->getValueKind(),
1574 OldMsg->getLeftLoc(),
1575 OldMsg->getClassReceiverTypeInfo(),
1576 OldMsg->getSelector(),
1577 SelLocs,
1578 OldMsg->getMethodDecl(),
1579 Args,
1580 OldMsg->getRightLoc(),
1581 OldMsg->isImplicit());
1582 break;
1583
1584 case ObjCMessageExpr::Instance:
1585 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1586 OldMsg->getValueKind(),
1587 OldMsg->getLeftLoc(),
1588 Base,
1589 OldMsg->getSelector(),
1590 SelLocs,
1591 OldMsg->getMethodDecl(),
1592 Args,
1593 OldMsg->getRightLoc(),
1594 OldMsg->isImplicit());
1595 break;
1596
1597 case ObjCMessageExpr::SuperClass:
1598 case ObjCMessageExpr::SuperInstance:
1599 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1600 OldMsg->getValueKind(),
1601 OldMsg->getLeftLoc(),
1602 OldMsg->getSuperLoc(),
1603 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1604 OldMsg->getSuperType(),
1605 OldMsg->getSelector(),
1606 SelLocs,
1607 OldMsg->getMethodDecl(),
1608 Args,
1609 OldMsg->getRightLoc(),
1610 OldMsg->isImplicit());
1611 break;
1612 }
1613
1614 Stmt *Replacement = SynthMessageExpr(NewMsg);
1615 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1616 return Replacement;
1617}
1618
1619/// SynthCountByEnumWithState - To print:
Fariborz Jahaniane38f08a2013-09-05 17:17:32 +00001620/// ((NSUInteger (*)
1621/// (id, SEL, struct __objcFastEnumerationState *, id *, NSUInteger))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001622/// (void *)objc_msgSend)((id)l_collection,
1623/// sel_registerName(
1624/// "countByEnumeratingWithState:objects:count:"),
1625/// &enumState,
Fariborz Jahaniane38f08a2013-09-05 17:17:32 +00001626/// (id *)__rw_items, (NSUInteger)16)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001627///
1628void RewriteModernObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahaniane38f08a2013-09-05 17:17:32 +00001629 buf += "((_WIN_NSUInteger (*) (id, SEL, struct __objcFastEnumerationState *, "
1630 "id *, _WIN_NSUInteger))(void *)objc_msgSend)";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001631 buf += "\n\t\t";
1632 buf += "((id)l_collection,\n\t\t";
1633 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1634 buf += "\n\t\t";
1635 buf += "&enumState, "
Fariborz Jahaniane38f08a2013-09-05 17:17:32 +00001636 "(id *)__rw_items, (_WIN_NSUInteger)16)";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001637}
1638
1639/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1640/// statement to exit to its outer synthesized loop.
1641///
1642Stmt *RewriteModernObjC::RewriteBreakStmt(BreakStmt *S) {
1643 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1644 return S;
1645 // replace break with goto __break_label
1646 std::string buf;
1647
1648 SourceLocation startLoc = S->getLocStart();
1649 buf = "goto __break_label_";
1650 buf += utostr(ObjCBcLabelNo.back());
1651 ReplaceText(startLoc, strlen("break"), buf);
1652
1653 return 0;
1654}
1655
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00001656void RewriteModernObjC::ConvertSourceLocationToLineDirective(
1657 SourceLocation Loc,
1658 std::string &LineString) {
Fariborz Jahanianada71912013-02-08 00:27:34 +00001659 if (Loc.isFileID() && GenerateLineInfo) {
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00001660 LineString += "\n#line ";
1661 PresumedLoc PLoc = SM->getPresumedLoc(Loc);
1662 LineString += utostr(PLoc.getLine());
1663 LineString += " \"";
1664 LineString += Lexer::Stringify(PLoc.getFilename());
1665 LineString += "\"\n";
1666 }
1667}
1668
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001669/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1670/// statement to continue with its inner synthesized loop.
1671///
1672Stmt *RewriteModernObjC::RewriteContinueStmt(ContinueStmt *S) {
1673 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1674 return S;
1675 // replace continue with goto __continue_label
1676 std::string buf;
1677
1678 SourceLocation startLoc = S->getLocStart();
1679 buf = "goto __continue_label_";
1680 buf += utostr(ObjCBcLabelNo.back());
1681 ReplaceText(startLoc, strlen("continue"), buf);
1682
1683 return 0;
1684}
1685
1686/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
1687/// It rewrites:
1688/// for ( type elem in collection) { stmts; }
1689
1690/// Into:
1691/// {
1692/// type elem;
1693/// struct __objcFastEnumerationState enumState = { 0 };
1694/// id __rw_items[16];
1695/// id l_collection = (id)collection;
Fariborz Jahaniane38f08a2013-09-05 17:17:32 +00001696/// NSUInteger limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001697/// objects:__rw_items count:16];
1698/// if (limit) {
1699/// unsigned long startMutations = *enumState.mutationsPtr;
1700/// do {
1701/// unsigned long counter = 0;
1702/// do {
1703/// if (startMutations != *enumState.mutationsPtr)
1704/// objc_enumerationMutation(l_collection);
1705/// elem = (type)enumState.itemsPtr[counter++];
1706/// stmts;
1707/// __continue_label: ;
1708/// } while (counter < limit);
Fariborz Jahaniane38f08a2013-09-05 17:17:32 +00001709/// } while ((limit = [l_collection countByEnumeratingWithState:&enumState
1710/// objects:__rw_items count:16]));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001711/// elem = nil;
1712/// __break_label: ;
1713/// }
1714/// else
1715/// elem = nil;
1716/// }
1717///
1718Stmt *RewriteModernObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1719 SourceLocation OrigEnd) {
1720 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1721 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1722 "ObjCForCollectionStmt Statement stack mismatch");
1723 assert(!ObjCBcLabelNo.empty() &&
1724 "ObjCForCollectionStmt - Label No stack empty");
1725
1726 SourceLocation startLoc = S->getLocStart();
1727 const char *startBuf = SM->getCharacterData(startLoc);
1728 StringRef elementName;
1729 std::string elementTypeAsString;
1730 std::string buf;
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00001731 // line directive first.
1732 SourceLocation ForEachLoc = S->getForLoc();
1733 ConvertSourceLocationToLineDirective(ForEachLoc, buf);
1734 buf += "{\n\t";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001735 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1736 // type elem;
1737 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1738 QualType ElementType = cast<ValueDecl>(D)->getType();
1739 if (ElementType->isObjCQualifiedIdType() ||
1740 ElementType->isObjCQualifiedInterfaceType())
1741 // Simply use 'id' for all qualified types.
1742 elementTypeAsString = "id";
1743 else
1744 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
1745 buf += elementTypeAsString;
1746 buf += " ";
1747 elementName = D->getName();
1748 buf += elementName;
1749 buf += ";\n\t";
1750 }
1751 else {
1752 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1753 elementName = DR->getDecl()->getName();
1754 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1755 if (VD->getType()->isObjCQualifiedIdType() ||
1756 VD->getType()->isObjCQualifiedInterfaceType())
1757 // Simply use 'id' for all qualified types.
1758 elementTypeAsString = "id";
1759 else
1760 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
1761 }
1762
1763 // struct __objcFastEnumerationState enumState = { 0 };
1764 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1765 // id __rw_items[16];
1766 buf += "id __rw_items[16];\n\t";
1767 // id l_collection = (id)
1768 buf += "id l_collection = (id)";
1769 // Find start location of 'collection' the hard way!
1770 const char *startCollectionBuf = startBuf;
1771 startCollectionBuf += 3; // skip 'for'
1772 startCollectionBuf = strchr(startCollectionBuf, '(');
1773 startCollectionBuf++; // skip '('
1774 // find 'in' and skip it.
1775 while (*startCollectionBuf != ' ' ||
1776 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1777 (*(startCollectionBuf+3) != ' ' &&
1778 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1779 startCollectionBuf++;
1780 startCollectionBuf += 3;
1781
1782 // Replace: "for (type element in" with string constructed thus far.
1783 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1784 // Replace ')' in for '(' type elem in collection ')' with ';'
1785 SourceLocation rightParenLoc = S->getRParenLoc();
1786 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1787 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
1788 buf = ";\n\t";
1789
1790 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1791 // objects:__rw_items count:16];
1792 // which is synthesized into:
Fariborz Jahaniane38f08a2013-09-05 17:17:32 +00001793 // NSUInteger limit =
1794 // ((NSUInteger (*)
1795 // (id, SEL, struct __objcFastEnumerationState *, id *, NSUInteger))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001796 // (void *)objc_msgSend)((id)l_collection,
1797 // sel_registerName(
1798 // "countByEnumeratingWithState:objects:count:"),
1799 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahaniane38f08a2013-09-05 17:17:32 +00001800 // (id *)__rw_items, (NSUInteger)16);
1801 buf += "_WIN_NSUInteger limit =\n\t\t";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001802 SynthCountByEnumWithState(buf);
1803 buf += ";\n\t";
1804 /// if (limit) {
1805 /// unsigned long startMutations = *enumState.mutationsPtr;
1806 /// do {
1807 /// unsigned long counter = 0;
1808 /// do {
1809 /// if (startMutations != *enumState.mutationsPtr)
1810 /// objc_enumerationMutation(l_collection);
1811 /// elem = (type)enumState.itemsPtr[counter++];
1812 buf += "if (limit) {\n\t";
1813 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1814 buf += "do {\n\t\t";
1815 buf += "unsigned long counter = 0;\n\t\t";
1816 buf += "do {\n\t\t\t";
1817 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1818 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1819 buf += elementName;
1820 buf += " = (";
1821 buf += elementTypeAsString;
1822 buf += ")enumState.itemsPtr[counter++];";
1823 // Replace ')' in for '(' type elem in collection ')' with all of these.
1824 ReplaceText(lparenLoc, 1, buf);
1825
1826 /// __continue_label: ;
1827 /// } while (counter < limit);
Fariborz Jahaniane38f08a2013-09-05 17:17:32 +00001828 /// } while ((limit = [l_collection countByEnumeratingWithState:&enumState
1829 /// objects:__rw_items count:16]));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001830 /// elem = nil;
1831 /// __break_label: ;
1832 /// }
1833 /// else
1834 /// elem = nil;
1835 /// }
1836 ///
1837 buf = ";\n\t";
1838 buf += "__continue_label_";
1839 buf += utostr(ObjCBcLabelNo.back());
1840 buf += ": ;";
1841 buf += "\n\t\t";
1842 buf += "} while (counter < limit);\n\t";
Fariborz Jahaniane38f08a2013-09-05 17:17:32 +00001843 buf += "} while ((limit = ";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001844 SynthCountByEnumWithState(buf);
Fariborz Jahaniane38f08a2013-09-05 17:17:32 +00001845 buf += "));\n\t";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001846 buf += elementName;
1847 buf += " = ((";
1848 buf += elementTypeAsString;
1849 buf += ")0);\n\t";
1850 buf += "__break_label_";
1851 buf += utostr(ObjCBcLabelNo.back());
1852 buf += ": ;\n\t";
1853 buf += "}\n\t";
1854 buf += "else\n\t\t";
1855 buf += elementName;
1856 buf += " = ((";
1857 buf += elementTypeAsString;
1858 buf += ")0);\n\t";
1859 buf += "}\n";
1860
1861 // Insert all these *after* the statement body.
1862 // FIXME: If this should support Obj-C++, support CXXTryStmt
1863 if (isa<CompoundStmt>(S->getBody())) {
1864 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
1865 InsertText(endBodyLoc, buf);
1866 } else {
1867 /* Need to treat single statements specially. For example:
1868 *
1869 * for (A *a in b) if (stuff()) break;
1870 * for (A *a in b) xxxyy;
1871 *
1872 * The following code simply scans ahead to the semi to find the actual end.
1873 */
1874 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1875 const char *semiBuf = strchr(stmtBuf, ';');
1876 assert(semiBuf && "Can't find ';'");
1877 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
1878 InsertText(endBodyLoc, buf);
1879 }
1880 Stmts.pop_back();
1881 ObjCBcLabelNo.pop_back();
1882 return 0;
1883}
1884
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001885static void Write_RethrowObject(std::string &buf) {
1886 buf += "{ struct _FIN { _FIN(id reth) : rethrow(reth) {}\n";
1887 buf += "\t~_FIN() { if (rethrow) objc_exception_throw(rethrow); }\n";
1888 buf += "\tid rethrow;\n";
1889 buf += "\t} _fin_force_rethow(_rethrow);";
1890}
1891
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001892/// RewriteObjCSynchronizedStmt -
1893/// This routine rewrites @synchronized(expr) stmt;
1894/// into:
1895/// objc_sync_enter(expr);
1896/// @try stmt @finally { objc_sync_exit(expr); }
1897///
1898Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1899 // Get the start location and compute the semi location.
1900 SourceLocation startLoc = S->getLocStart();
1901 const char *startBuf = SM->getCharacterData(startLoc);
1902
1903 assert((*startBuf == '@') && "bogus @synchronized location");
1904
1905 std::string buf;
Fariborz Jahanian43f4f1e2012-11-07 00:43:05 +00001906 SourceLocation SynchLoc = S->getAtSynchronizedLoc();
1907 ConvertSourceLocationToLineDirective(SynchLoc, buf);
1908 buf += "{ id _rethrow = 0; id _sync_obj = ";
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001909
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001910 const char *lparenBuf = startBuf;
1911 while (*lparenBuf != '(') lparenBuf++;
1912 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001913
1914 buf = "; objc_sync_enter(_sync_obj);\n";
1915 buf += "try {\n\tstruct _SYNC_EXIT { _SYNC_EXIT(id arg) : sync_exit(arg) {}";
1916 buf += "\n\t~_SYNC_EXIT() {objc_sync_exit(sync_exit);}";
1917 buf += "\n\tid sync_exit;";
1918 buf += "\n\t} _sync_exit(_sync_obj);\n";
1919
1920 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1921 // the sync expression is typically a message expression that's already
1922 // been rewritten! (which implies the SourceLocation's are invalid).
1923 SourceLocation RParenExprLoc = S->getSynchBody()->getLocStart();
1924 const char *RParenExprLocBuf = SM->getCharacterData(RParenExprLoc);
1925 while (*RParenExprLocBuf != ')') RParenExprLocBuf--;
1926 RParenExprLoc = startLoc.getLocWithOffset(RParenExprLocBuf-startBuf);
1927
1928 SourceLocation LBranceLoc = S->getSynchBody()->getLocStart();
1929 const char *LBraceLocBuf = SM->getCharacterData(LBranceLoc);
1930 assert (*LBraceLocBuf == '{');
1931 ReplaceText(RParenExprLoc, (LBraceLocBuf - SM->getCharacterData(RParenExprLoc) + 1), buf);
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001932
Fariborz Jahanianb655bf02012-03-16 21:43:45 +00001933 SourceLocation startRBraceLoc = S->getSynchBody()->getLocEnd();
Matt Beaumont-Gay9ab511c2012-03-16 22:20:39 +00001934 assert((*SM->getCharacterData(startRBraceLoc) == '}') &&
1935 "bogus @synchronized block");
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001936
1937 buf = "} catch (id e) {_rethrow = e;}\n";
1938 Write_RethrowObject(buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001939 buf += "}\n";
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001940 buf += "}\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001941
Fariborz Jahanianb655bf02012-03-16 21:43:45 +00001942 ReplaceText(startRBraceLoc, 1, buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001943
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001944 return 0;
1945}
1946
1947void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S)
1948{
1949 // Perform a bottom up traversal of all children.
1950 for (Stmt::child_range CI = S->children(); CI; ++CI)
1951 if (*CI)
1952 WarnAboutReturnGotoStmts(*CI);
1953
1954 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
1955 Diags.Report(Context->getFullLoc(S->getLocStart()),
1956 TryFinallyContainsReturnDiag);
1957 }
1958 return;
1959}
1960
Fariborz Jahanian042b91d2012-05-23 23:47:20 +00001961Stmt *RewriteModernObjC::RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) {
1962 SourceLocation startLoc = S->getAtLoc();
1963 ReplaceText(startLoc, strlen("@autoreleasepool"), "/* @autoreleasepool */");
Fariborz Jahanianc9b72b62012-05-24 22:59:56 +00001964 ReplaceText(S->getSubStmt()->getLocStart(), 1,
1965 "{ __AtAutoreleasePool __autoreleasepool; ");
Fariborz Jahanian042b91d2012-05-23 23:47:20 +00001966
1967 return 0;
1968}
1969
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001970Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001971 ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt();
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001972 bool noCatch = S->getNumCatchStmts() == 0;
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001973 std::string buf;
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00001974 SourceLocation TryLocation = S->getAtTryLoc();
1975 ConvertSourceLocationToLineDirective(TryLocation, buf);
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001976
1977 if (finalStmt) {
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001978 if (noCatch)
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00001979 buf += "{ id volatile _rethrow = 0;\n";
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001980 else {
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00001981 buf += "{ id volatile _rethrow = 0;\ntry {\n";
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001982 }
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001983 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001984 // Get the start location and compute the semi location.
1985 SourceLocation startLoc = S->getLocStart();
1986 const char *startBuf = SM->getCharacterData(startLoc);
1987
1988 assert((*startBuf == '@') && "bogus @try location");
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001989 if (finalStmt)
1990 ReplaceText(startLoc, 1, buf);
1991 else
1992 // @try -> try
1993 ReplaceText(startLoc, 1, "");
1994
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001995 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1996 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Fariborz Jahanian4c148812012-03-15 20:11:10 +00001997 VarDecl *catchDecl = Catch->getCatchParamDecl();
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001998
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001999 startLoc = Catch->getLocStart();
Fariborz Jahanian4c148812012-03-15 20:11:10 +00002000 bool AtRemoved = false;
2001 if (catchDecl) {
2002 QualType t = catchDecl->getType();
2003 if (const ObjCObjectPointerType *Ptr = t->getAs<ObjCObjectPointerType>()) {
2004 // Should be a pointer to a class.
2005 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
2006 if (IDecl) {
2007 std::string Result;
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00002008 ConvertSourceLocationToLineDirective(Catch->getLocStart(), Result);
2009
Fariborz Jahanian4c148812012-03-15 20:11:10 +00002010 startBuf = SM->getCharacterData(startLoc);
2011 assert((*startBuf == '@') && "bogus @catch location");
2012 SourceLocation rParenLoc = Catch->getRParenLoc();
2013 const char *rParenBuf = SM->getCharacterData(rParenLoc);
2014
2015 // _objc_exc_Foo *_e as argument to catch.
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00002016 Result += "catch (_objc_exc_"; Result += IDecl->getNameAsString();
Fariborz Jahanian4c148812012-03-15 20:11:10 +00002017 Result += " *_"; Result += catchDecl->getNameAsString();
2018 Result += ")";
2019 ReplaceText(startLoc, rParenBuf-startBuf+1, Result);
2020 // Foo *e = (Foo *)_e;
2021 Result.clear();
2022 Result = "{ ";
2023 Result += IDecl->getNameAsString();
2024 Result += " *"; Result += catchDecl->getNameAsString();
2025 Result += " = ("; Result += IDecl->getNameAsString(); Result += "*)";
2026 Result += "_"; Result += catchDecl->getNameAsString();
2027
2028 Result += "; ";
2029 SourceLocation lBraceLoc = Catch->getCatchBody()->getLocStart();
2030 ReplaceText(lBraceLoc, 1, Result);
2031 AtRemoved = true;
2032 }
2033 }
2034 }
2035 if (!AtRemoved)
2036 // @catch -> catch
2037 ReplaceText(startLoc, 1, "");
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00002038
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002039 }
Fariborz Jahanian220419a2012-03-15 23:50:33 +00002040 if (finalStmt) {
2041 buf.clear();
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00002042 SourceLocation FinallyLoc = finalStmt->getLocStart();
2043
2044 if (noCatch) {
2045 ConvertSourceLocationToLineDirective(FinallyLoc, buf);
2046 buf += "catch (id e) {_rethrow = e;}\n";
2047 }
2048 else {
2049 buf += "}\n";
2050 ConvertSourceLocationToLineDirective(FinallyLoc, buf);
2051 buf += "catch (id e) {_rethrow = e;}\n";
2052 }
2053
Fariborz Jahanian220419a2012-03-15 23:50:33 +00002054 SourceLocation startFinalLoc = finalStmt->getLocStart();
2055 ReplaceText(startFinalLoc, 8, buf);
2056 Stmt *body = finalStmt->getFinallyBody();
2057 SourceLocation startFinalBodyLoc = body->getLocStart();
2058 buf.clear();
Fariborz Jahanian542125f2012-03-16 21:33:16 +00002059 Write_RethrowObject(buf);
Fariborz Jahanian220419a2012-03-15 23:50:33 +00002060 ReplaceText(startFinalBodyLoc, 1, buf);
2061
2062 SourceLocation endFinalBodyLoc = body->getLocEnd();
2063 ReplaceText(endFinalBodyLoc, 1, "}\n}");
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00002064 // Now check for any return/continue/go statements within the @try.
2065 WarnAboutReturnGotoStmts(S->getTryBody());
Fariborz Jahanian220419a2012-03-15 23:50:33 +00002066 }
2067
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002068 return 0;
2069}
2070
2071// This can't be done with ReplaceStmt(S, ThrowExpr), since
2072// the throw expression is typically a message expression that's already
2073// been rewritten! (which implies the SourceLocation's are invalid).
2074Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
2075 // Get the start location and compute the semi location.
2076 SourceLocation startLoc = S->getLocStart();
2077 const char *startBuf = SM->getCharacterData(startLoc);
2078
2079 assert((*startBuf == '@') && "bogus @throw location");
2080
2081 std::string buf;
2082 /* void objc_exception_throw(id) __attribute__((noreturn)); */
2083 if (S->getThrowExpr())
2084 buf = "objc_exception_throw(";
Fariborz Jahanian40539462012-03-16 16:52:06 +00002085 else
2086 buf = "throw";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002087
2088 // handle "@ throw" correctly.
2089 const char *wBuf = strchr(startBuf, 'w');
2090 assert((*wBuf == 'w') && "@throw: can't find 'w'");
2091 ReplaceText(startLoc, wBuf-startBuf+1, buf);
2092
Fariborz Jahaniana09cd812013-02-11 19:30:33 +00002093 SourceLocation endLoc = S->getLocEnd();
2094 const char *endBuf = SM->getCharacterData(endLoc);
2095 const char *semiBuf = strchr(endBuf, ';');
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002096 assert((*semiBuf == ';') && "@throw: can't find ';'");
2097 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Fariborz Jahanian40539462012-03-16 16:52:06 +00002098 if (S->getThrowExpr())
2099 ReplaceText(semiLoc, 1, ");");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002100 return 0;
2101}
2102
2103Stmt *RewriteModernObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
2104 // Create a new string expression.
2105 QualType StrType = Context->getPointerType(Context->CharTy);
2106 std::string StrEncoding;
2107 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
2108 Expr *Replacement = StringLiteral::Create(*Context, StrEncoding,
2109 StringLiteral::Ascii, false,
2110 StrType, SourceLocation());
2111 ReplaceStmt(Exp, Replacement);
2112
2113 // Replace this subexpr in the parent.
2114 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2115 return Replacement;
2116}
2117
2118Stmt *RewriteModernObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
2119 if (!SelGetUidFunctionDecl)
2120 SynthSelGetUidFunctionDecl();
2121 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2122 // Create a call to sel_registerName("selName").
2123 SmallVector<Expr*, 8> SelExprs;
2124 QualType argType = Context->getPointerType(Context->CharTy);
2125 SelExprs.push_back(StringLiteral::Create(*Context,
2126 Exp->getSelector().getAsString(),
2127 StringLiteral::Ascii, false,
2128 argType, SourceLocation()));
2129 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2130 &SelExprs[0], SelExprs.size());
2131 ReplaceStmt(Exp, SelExp);
2132 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2133 return SelExp;
2134}
2135
2136CallExpr *RewriteModernObjC::SynthesizeCallToFunctionDecl(
2137 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2138 SourceLocation EndLoc) {
2139 // Get the type, we will need to reference it in a couple spots.
2140 QualType msgSendType = FD->getType();
2141
2142 // Create a reference to the objc_msgSend() declaration.
2143 DeclRefExpr *DRE =
John McCallf4b88a42012-03-10 09:33:50 +00002144 new (Context) DeclRefExpr(FD, false, msgSendType, VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002145
2146 // Now, we cast the reference to a pointer to the objc_msgSend type.
2147 QualType pToFunc = Context->getPointerType(msgSendType);
2148 ImplicitCastExpr *ICE =
2149 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
2150 DRE, 0, VK_RValue);
2151
2152 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2153
2154 CallExpr *Exp =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002155 new (Context) CallExpr(*Context, ICE, llvm::makeArrayRef(args, nargs),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002156 FT->getCallResultType(*Context),
2157 VK_RValue, EndLoc);
2158 return Exp;
2159}
2160
2161static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2162 const char *&startRef, const char *&endRef) {
2163 while (startBuf < endBuf) {
2164 if (*startBuf == '<')
2165 startRef = startBuf; // mark the start.
2166 if (*startBuf == '>') {
2167 if (startRef && *startRef == '<') {
2168 endRef = startBuf; // mark the end.
2169 return true;
2170 }
2171 return false;
2172 }
2173 startBuf++;
2174 }
2175 return false;
2176}
2177
2178static void scanToNextArgument(const char *&argRef) {
2179 int angle = 0;
2180 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2181 if (*argRef == '<')
2182 angle++;
2183 else if (*argRef == '>')
2184 angle--;
2185 argRef++;
2186 }
2187 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2188}
2189
2190bool RewriteModernObjC::needToScanForQualifiers(QualType T) {
2191 if (T->isObjCQualifiedIdType())
2192 return true;
2193 if (const PointerType *PT = T->getAs<PointerType>()) {
2194 if (PT->getPointeeType()->isObjCQualifiedIdType())
2195 return true;
2196 }
2197 if (T->isObjCObjectPointerType()) {
2198 T = T->getPointeeType();
2199 return T->isObjCQualifiedInterfaceType();
2200 }
2201 if (T->isArrayType()) {
2202 QualType ElemTy = Context->getBaseElementType(T);
2203 return needToScanForQualifiers(ElemTy);
2204 }
2205 return false;
2206}
2207
2208void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2209 QualType Type = E->getType();
2210 if (needToScanForQualifiers(Type)) {
2211 SourceLocation Loc, EndLoc;
2212
2213 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2214 Loc = ECE->getLParenLoc();
2215 EndLoc = ECE->getRParenLoc();
2216 } else {
2217 Loc = E->getLocStart();
2218 EndLoc = E->getLocEnd();
2219 }
2220 // This will defend against trying to rewrite synthesized expressions.
2221 if (Loc.isInvalid() || EndLoc.isInvalid())
2222 return;
2223
2224 const char *startBuf = SM->getCharacterData(Loc);
2225 const char *endBuf = SM->getCharacterData(EndLoc);
2226 const char *startRef = 0, *endRef = 0;
2227 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2228 // Get the locations of the startRef, endRef.
2229 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2230 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2231 // Comment out the protocol references.
2232 InsertText(LessLoc, "/*");
2233 InsertText(GreaterLoc, "*/");
2234 }
2235 }
2236}
2237
2238void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2239 SourceLocation Loc;
2240 QualType Type;
2241 const FunctionProtoType *proto = 0;
2242 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2243 Loc = VD->getLocation();
2244 Type = VD->getType();
2245 }
2246 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2247 Loc = FD->getLocation();
2248 // Check for ObjC 'id' and class types that have been adorned with protocol
2249 // information (id<p>, C<p>*). The protocol references need to be rewritten!
2250 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2251 assert(funcType && "missing function type");
2252 proto = dyn_cast<FunctionProtoType>(funcType);
2253 if (!proto)
2254 return;
2255 Type = proto->getResultType();
2256 }
2257 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2258 Loc = FD->getLocation();
2259 Type = FD->getType();
2260 }
Fariborz Jahanianf9f30792013-04-03 19:11:21 +00002261 else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(Dcl)) {
2262 Loc = TD->getLocation();
2263 Type = TD->getUnderlyingType();
2264 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002265 else
2266 return;
2267
2268 if (needToScanForQualifiers(Type)) {
2269 // Since types are unique, we need to scan the buffer.
2270
2271 const char *endBuf = SM->getCharacterData(Loc);
2272 const char *startBuf = endBuf;
2273 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
2274 startBuf--; // scan backward (from the decl location) for return type.
2275 const char *startRef = 0, *endRef = 0;
2276 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2277 // Get the locations of the startRef, endRef.
2278 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2279 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2280 // Comment out the protocol references.
2281 InsertText(LessLoc, "/*");
2282 InsertText(GreaterLoc, "*/");
2283 }
2284 }
2285 if (!proto)
2286 return; // most likely, was a variable
2287 // Now check arguments.
2288 const char *startBuf = SM->getCharacterData(Loc);
2289 const char *startFuncBuf = startBuf;
2290 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2291 if (needToScanForQualifiers(proto->getArgType(i))) {
2292 // Since types are unique, we need to scan the buffer.
2293
2294 const char *endBuf = startBuf;
2295 // scan forward (from the decl location) for argument types.
2296 scanToNextArgument(endBuf);
2297 const char *startRef = 0, *endRef = 0;
2298 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2299 // Get the locations of the startRef, endRef.
2300 SourceLocation LessLoc =
2301 Loc.getLocWithOffset(startRef-startFuncBuf);
2302 SourceLocation GreaterLoc =
2303 Loc.getLocWithOffset(endRef-startFuncBuf+1);
2304 // Comment out the protocol references.
2305 InsertText(LessLoc, "/*");
2306 InsertText(GreaterLoc, "*/");
2307 }
2308 startBuf = ++endBuf;
2309 }
2310 else {
2311 // If the function name is derived from a macro expansion, then the
2312 // argument buffer will not follow the name. Need to speak with Chris.
2313 while (*startBuf && *startBuf != ')' && *startBuf != ',')
2314 startBuf++; // scan forward (from the decl location) for argument types.
2315 startBuf++;
2316 }
2317 }
2318}
2319
2320void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) {
2321 QualType QT = ND->getType();
2322 const Type* TypePtr = QT->getAs<Type>();
2323 if (!isa<TypeOfExprType>(TypePtr))
2324 return;
2325 while (isa<TypeOfExprType>(TypePtr)) {
2326 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2327 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2328 TypePtr = QT->getAs<Type>();
2329 }
2330 // FIXME. This will not work for multiple declarators; as in:
2331 // __typeof__(a) b,c,d;
2332 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2333 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2334 const char *startBuf = SM->getCharacterData(DeclLoc);
2335 if (ND->getInit()) {
2336 std::string Name(ND->getNameAsString());
2337 TypeAsString += " " + Name + " = ";
2338 Expr *E = ND->getInit();
2339 SourceLocation startLoc;
2340 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2341 startLoc = ECE->getLParenLoc();
2342 else
2343 startLoc = E->getLocStart();
2344 startLoc = SM->getExpansionLoc(startLoc);
2345 const char *endBuf = SM->getCharacterData(startLoc);
2346 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2347 }
2348 else {
2349 SourceLocation X = ND->getLocEnd();
2350 X = SM->getExpansionLoc(X);
2351 const char *endBuf = SM->getCharacterData(X);
2352 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2353 }
2354}
2355
2356// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2357void RewriteModernObjC::SynthSelGetUidFunctionDecl() {
2358 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2359 SmallVector<QualType, 16> ArgTys;
2360 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2361 QualType getFuncType =
Jordan Rosebea522f2013-03-08 21:51:21 +00002362 getSimpleFunctionType(Context->getObjCSelType(), ArgTys);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002363 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002364 SourceLocation(),
2365 SourceLocation(),
2366 SelGetUidIdent, getFuncType, 0,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002367 SC_Extern);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002368}
2369
2370void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2371 // declared in <objc/objc.h>
2372 if (FD->getIdentifier() &&
2373 FD->getName() == "sel_registerName") {
2374 SelGetUidFunctionDecl = FD;
2375 return;
2376 }
2377 RewriteObjCQualifiedInterfaceTypes(FD);
2378}
2379
2380void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2381 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2382 const char *argPtr = TypeString.c_str();
2383 if (!strchr(argPtr, '^')) {
2384 Str += TypeString;
2385 return;
2386 }
2387 while (*argPtr) {
2388 Str += (*argPtr == '^' ? '*' : *argPtr);
2389 argPtr++;
2390 }
2391}
2392
2393// FIXME. Consolidate this routine with RewriteBlockPointerType.
2394void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2395 ValueDecl *VD) {
2396 QualType Type = VD->getType();
2397 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2398 const char *argPtr = TypeString.c_str();
2399 int paren = 0;
2400 while (*argPtr) {
2401 switch (*argPtr) {
2402 case '(':
2403 Str += *argPtr;
2404 paren++;
2405 break;
2406 case ')':
2407 Str += *argPtr;
2408 paren--;
2409 break;
2410 case '^':
2411 Str += '*';
2412 if (paren == 1)
2413 Str += VD->getNameAsString();
2414 break;
2415 default:
2416 Str += *argPtr;
2417 break;
2418 }
2419 argPtr++;
2420 }
2421}
2422
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00002423void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2424 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2425 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2426 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2427 if (!proto)
2428 return;
2429 QualType Type = proto->getResultType();
2430 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2431 FdStr += " ";
2432 FdStr += FD->getName();
2433 FdStr += "(";
2434 unsigned numArgs = proto->getNumArgs();
2435 for (unsigned i = 0; i < numArgs; i++) {
2436 QualType ArgType = proto->getArgType(i);
2437 RewriteBlockPointerType(FdStr, ArgType);
2438 if (i+1 < numArgs)
2439 FdStr += ", ";
2440 }
Fariborz Jahanianb5863da2012-04-19 16:30:28 +00002441 if (FD->isVariadic()) {
2442 FdStr += (numArgs > 0) ? ", ...);\n" : "...);\n";
2443 }
2444 else
2445 FdStr += ");\n";
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00002446 InsertText(FunLocStart, FdStr);
2447}
2448
Benjamin Kramere5753592013-09-09 14:48:42 +00002449// SynthSuperConstructorFunctionDecl - id __rw_objc_super(id obj, id super);
2450void RewriteModernObjC::SynthSuperConstructorFunctionDecl() {
2451 if (SuperConstructorFunctionDecl)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002452 return;
2453 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2454 SmallVector<QualType, 16> ArgTys;
2455 QualType argT = Context->getObjCIdType();
2456 assert(!argT.isNull() && "Can't find 'id' type");
2457 ArgTys.push_back(argT);
2458 ArgTys.push_back(argT);
2459 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rosebea522f2013-03-08 21:51:21 +00002460 ArgTys);
Benjamin Kramere5753592013-09-09 14:48:42 +00002461 SuperConstructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002462 SourceLocation(),
2463 SourceLocation(),
2464 msgSendIdent, msgSendType,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002465 0, SC_Extern);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002466}
2467
2468// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2469void RewriteModernObjC::SynthMsgSendFunctionDecl() {
2470 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2471 SmallVector<QualType, 16> ArgTys;
2472 QualType argT = Context->getObjCIdType();
2473 assert(!argT.isNull() && "Can't find 'id' type");
2474 ArgTys.push_back(argT);
2475 argT = Context->getObjCSelType();
2476 assert(!argT.isNull() && "Can't find 'SEL' type");
2477 ArgTys.push_back(argT);
2478 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rosebea522f2013-03-08 21:51:21 +00002479 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002480 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002481 SourceLocation(),
2482 SourceLocation(),
2483 msgSendIdent, msgSendType, 0,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002484 SC_Extern);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002485}
2486
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002487// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(void);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002488void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() {
2489 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002490 SmallVector<QualType, 2> ArgTys;
2491 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002492 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rosebea522f2013-03-08 21:51:21 +00002493 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002494 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002495 SourceLocation(),
2496 SourceLocation(),
2497 msgSendIdent, msgSendType, 0,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002498 SC_Extern);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002499}
2500
2501// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2502void RewriteModernObjC::SynthMsgSendStretFunctionDecl() {
2503 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2504 SmallVector<QualType, 16> ArgTys;
2505 QualType argT = Context->getObjCIdType();
2506 assert(!argT.isNull() && "Can't find 'id' type");
2507 ArgTys.push_back(argT);
2508 argT = Context->getObjCSelType();
2509 assert(!argT.isNull() && "Can't find 'SEL' type");
2510 ArgTys.push_back(argT);
2511 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rosebea522f2013-03-08 21:51:21 +00002512 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002513 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002514 SourceLocation(),
2515 SourceLocation(),
2516 msgSendIdent, msgSendType, 0,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002517 SC_Extern);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002518}
2519
2520// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002521// id objc_msgSendSuper_stret(void);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002522void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() {
2523 IdentifierInfo *msgSendIdent =
2524 &Context->Idents.get("objc_msgSendSuper_stret");
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002525 SmallVector<QualType, 2> ArgTys;
2526 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002527 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rosebea522f2013-03-08 21:51:21 +00002528 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002529 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2530 SourceLocation(),
2531 SourceLocation(),
Chad Rosiere3b29882013-01-04 22:40:33 +00002532 msgSendIdent,
2533 msgSendType, 0,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002534 SC_Extern);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002535}
2536
2537// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2538void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() {
2539 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2540 SmallVector<QualType, 16> ArgTys;
2541 QualType argT = Context->getObjCIdType();
2542 assert(!argT.isNull() && "Can't find 'id' type");
2543 ArgTys.push_back(argT);
2544 argT = Context->getObjCSelType();
2545 assert(!argT.isNull() && "Can't find 'SEL' type");
2546 ArgTys.push_back(argT);
2547 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
Jordan Rosebea522f2013-03-08 21:51:21 +00002548 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002549 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002550 SourceLocation(),
2551 SourceLocation(),
2552 msgSendIdent, msgSendType, 0,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002553 SC_Extern);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002554}
2555
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00002556// SynthGetClassFunctionDecl - Class objc_getClass(const char *name);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002557void RewriteModernObjC::SynthGetClassFunctionDecl() {
2558 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2559 SmallVector<QualType, 16> ArgTys;
2560 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00002561 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Jordan Rosebea522f2013-03-08 21:51:21 +00002562 ArgTys);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002563 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002564 SourceLocation(),
2565 SourceLocation(),
2566 getClassIdent, getClassType, 0,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002567 SC_Extern);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002568}
2569
2570// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2571void RewriteModernObjC::SynthGetSuperClassFunctionDecl() {
2572 IdentifierInfo *getSuperClassIdent =
2573 &Context->Idents.get("class_getSuperclass");
2574 SmallVector<QualType, 16> ArgTys;
2575 ArgTys.push_back(Context->getObjCClassType());
2576 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Jordan Rosebea522f2013-03-08 21:51:21 +00002577 ArgTys);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002578 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2579 SourceLocation(),
2580 SourceLocation(),
2581 getSuperClassIdent,
2582 getClassType, 0,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002583 SC_Extern);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002584}
2585
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00002586// SynthGetMetaClassFunctionDecl - Class objc_getMetaClass(const char *name);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002587void RewriteModernObjC::SynthGetMetaClassFunctionDecl() {
2588 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2589 SmallVector<QualType, 16> ArgTys;
2590 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00002591 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Jordan Rosebea522f2013-03-08 21:51:21 +00002592 ArgTys);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002593 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002594 SourceLocation(),
2595 SourceLocation(),
2596 getClassIdent, getClassType,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002597 0, SC_Extern);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002598}
2599
2600Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
2601 QualType strType = getConstantStringStructType();
2602
2603 std::string S = "__NSConstantStringImpl_";
2604
2605 std::string tmpName = InFileName;
2606 unsigned i;
2607 for (i=0; i < tmpName.length(); i++) {
2608 char c = tmpName.at(i);
2609 // replace any non alphanumeric characters with '_'.
Jordan Rose3f6f51e2013-02-08 22:30:41 +00002610 if (!isAlphanumeric(c))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002611 tmpName[i] = '_';
2612 }
2613 S += tmpName;
2614 S += "_";
2615 S += utostr(NumObjCStringLiterals++);
2616
2617 Preamble += "static __NSConstantStringImpl " + S;
2618 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2619 Preamble += "0x000007c8,"; // utf8_str
2620 // The pretty printer for StringLiteral handles escape characters properly.
2621 std::string prettyBufS;
2622 llvm::raw_string_ostream prettyBuf(prettyBufS);
Richard Smithd1420c62012-08-16 03:56:14 +00002623 Exp->getString()->printPretty(prettyBuf, 0, PrintingPolicy(LangOpts));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002624 Preamble += prettyBuf.str();
2625 Preamble += ",";
2626 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2627
2628 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2629 SourceLocation(), &Context->Idents.get(S),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002630 strType, 0, SC_Static);
John McCallf4b88a42012-03-10 09:33:50 +00002631 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002632 SourceLocation());
2633 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
2634 Context->getPointerType(DRE->getType()),
2635 VK_RValue, OK_Ordinary,
2636 SourceLocation());
2637 // cast to NSConstantString *
2638 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2639 CK_CPointerToObjCPointerCast, Unop);
2640 ReplaceStmt(Exp, cast);
2641 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2642 return cast;
2643}
2644
Fariborz Jahanian55947042012-03-27 20:17:30 +00002645Stmt *RewriteModernObjC::RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp) {
2646 unsigned IntSize =
2647 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
2648
2649 Expr *FlagExp = IntegerLiteral::Create(*Context,
2650 llvm::APInt(IntSize, Exp->getValue()),
2651 Context->IntTy, Exp->getLocation());
2652 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Context->ObjCBuiltinBoolTy,
2653 CK_BitCast, FlagExp);
2654 ParenExpr *PE = new (Context) ParenExpr(Exp->getLocation(), Exp->getExprLoc(),
2655 cast);
2656 ReplaceStmt(Exp, PE);
2657 return PE;
2658}
2659
Patrick Beardeb382ec2012-04-19 00:25:12 +00002660Stmt *RewriteModernObjC::RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp) {
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002661 // synthesize declaration of helper functions needed in this routine.
2662 if (!SelGetUidFunctionDecl)
2663 SynthSelGetUidFunctionDecl();
2664 // use objc_msgSend() for all.
2665 if (!MsgSendFunctionDecl)
2666 SynthMsgSendFunctionDecl();
2667 if (!GetClassFunctionDecl)
2668 SynthGetClassFunctionDecl();
2669
2670 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2671 SourceLocation StartLoc = Exp->getLocStart();
2672 SourceLocation EndLoc = Exp->getLocEnd();
2673
2674 // Synthesize a call to objc_msgSend().
2675 SmallVector<Expr*, 4> MsgExprs;
2676 SmallVector<Expr*, 4> ClsExprs;
2677 QualType argType = Context->getPointerType(Context->CharTy);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002678
Patrick Beardeb382ec2012-04-19 00:25:12 +00002679 // Create a call to objc_getClass("<BoxingClass>"). It will be the 1st argument.
2680 ObjCMethodDecl *BoxingMethod = Exp->getBoxingMethod();
2681 ObjCInterfaceDecl *BoxingClass = BoxingMethod->getClassInterface();
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002682
Patrick Beardeb382ec2012-04-19 00:25:12 +00002683 IdentifierInfo *clsName = BoxingClass->getIdentifier();
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002684 ClsExprs.push_back(StringLiteral::Create(*Context,
2685 clsName->getName(),
2686 StringLiteral::Ascii, false,
2687 argType, SourceLocation()));
2688 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2689 &ClsExprs[0],
2690 ClsExprs.size(),
2691 StartLoc, EndLoc);
2692 MsgExprs.push_back(Cls);
2693
Patrick Beardeb382ec2012-04-19 00:25:12 +00002694 // Create a call to sel_registerName("<BoxingMethod>:"), etc.
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002695 // it will be the 2nd argument.
2696 SmallVector<Expr*, 4> SelExprs;
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002697 SelExprs.push_back(StringLiteral::Create(*Context,
Patrick Beardeb382ec2012-04-19 00:25:12 +00002698 BoxingMethod->getSelector().getAsString(),
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002699 StringLiteral::Ascii, false,
2700 argType, SourceLocation()));
2701 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2702 &SelExprs[0], SelExprs.size(),
2703 StartLoc, EndLoc);
2704 MsgExprs.push_back(SelExp);
2705
Patrick Beardeb382ec2012-04-19 00:25:12 +00002706 // User provided sub-expression is the 3rd, and last, argument.
2707 Expr *subExpr = Exp->getSubExpr();
2708 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(subExpr)) {
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002709 QualType type = ICE->getType();
2710 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2711 CastKind CK = CK_BitCast;
2712 if (SubExpr->getType()->isIntegralType(*Context) && type->isBooleanType())
2713 CK = CK_IntegralToBoolean;
Patrick Beardeb382ec2012-04-19 00:25:12 +00002714 subExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, subExpr);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002715 }
Patrick Beardeb382ec2012-04-19 00:25:12 +00002716 MsgExprs.push_back(subExpr);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002717
2718 SmallVector<QualType, 4> ArgTypes;
2719 ArgTypes.push_back(Context->getObjCIdType());
2720 ArgTypes.push_back(Context->getObjCSelType());
Patrick Beardeb382ec2012-04-19 00:25:12 +00002721 for (ObjCMethodDecl::param_iterator PI = BoxingMethod->param_begin(),
2722 E = BoxingMethod->param_end(); PI != E; ++PI)
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002723 ArgTypes.push_back((*PI)->getType());
Patrick Beardeb382ec2012-04-19 00:25:12 +00002724
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002725 QualType returnType = Exp->getType();
2726 // Get the type, we will need to reference it in a couple spots.
2727 QualType msgSendType = MsgSendFlavor->getType();
2728
2729 // Create a reference to the objc_msgSend() declaration.
2730 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2731 VK_LValue, SourceLocation());
2732
2733 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
Patrick Beardeb382ec2012-04-19 00:25:12 +00002734 Context->getPointerType(Context->VoidTy),
2735 CK_BitCast, DRE);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002736
2737 // Now do the "normal" pointer to function cast.
2738 QualType castType =
Jordan Rosebea522f2013-03-08 21:51:21 +00002739 getSimpleFunctionType(returnType, ArgTypes, BoxingMethod->isVariadic());
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002740 castType = Context->getPointerType(castType);
2741 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2742 cast);
2743
2744 // Don't forget the parens to enforce the proper binding.
2745 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2746
2747 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002748 CallExpr *CE = new (Context) CallExpr(*Context, PE, MsgExprs,
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002749 FT->getResultType(), VK_RValue,
2750 EndLoc);
2751 ReplaceStmt(Exp, CE);
2752 return CE;
2753}
2754
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002755Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) {
2756 // synthesize declaration of helper functions needed in this routine.
2757 if (!SelGetUidFunctionDecl)
2758 SynthSelGetUidFunctionDecl();
2759 // use objc_msgSend() for all.
2760 if (!MsgSendFunctionDecl)
2761 SynthMsgSendFunctionDecl();
2762 if (!GetClassFunctionDecl)
2763 SynthGetClassFunctionDecl();
2764
2765 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2766 SourceLocation StartLoc = Exp->getLocStart();
2767 SourceLocation EndLoc = Exp->getLocEnd();
2768
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002769 // Build the expression: __NSContainer_literal(int, ...).arr
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002770 QualType IntQT = Context->IntTy;
2771 QualType NSArrayFType =
Jordan Rosebea522f2013-03-08 21:51:21 +00002772 getSimpleFunctionType(Context->VoidTy, IntQT, true);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002773 std::string NSArrayFName("__NSContainer_literal");
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002774 FunctionDecl *NSArrayFD = SynthBlockInitFunctionDecl(NSArrayFName);
2775 DeclRefExpr *NSArrayDRE =
2776 new (Context) DeclRefExpr(NSArrayFD, false, NSArrayFType, VK_RValue,
2777 SourceLocation());
2778
2779 SmallVector<Expr*, 16> InitExprs;
2780 unsigned NumElements = Exp->getNumElements();
2781 unsigned UnsignedIntSize =
2782 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2783 Expr *count = IntegerLiteral::Create(*Context,
2784 llvm::APInt(UnsignedIntSize, NumElements),
2785 Context->UnsignedIntTy, SourceLocation());
2786 InitExprs.push_back(count);
2787 for (unsigned i = 0; i < NumElements; i++)
2788 InitExprs.push_back(Exp->getElement(i));
2789 Expr *NSArrayCallExpr =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002790 new (Context) CallExpr(*Context, NSArrayDRE, InitExprs,
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002791 NSArrayFType, VK_LValue, SourceLocation());
2792
2793 FieldDecl *ARRFD = FieldDecl::Create(*Context, 0, SourceLocation(),
2794 SourceLocation(),
2795 &Context->Idents.get("arr"),
2796 Context->getPointerType(Context->VoidPtrTy), 0,
2797 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00002798 ICIS_NoInit);
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002799 MemberExpr *ArrayLiteralME =
2800 new (Context) MemberExpr(NSArrayCallExpr, false, ARRFD,
2801 SourceLocation(),
2802 ARRFD->getType(), VK_LValue,
2803 OK_Ordinary);
2804 QualType ConstIdT = Context->getObjCIdType().withConst();
2805 CStyleCastExpr * ArrayLiteralObjects =
2806 NoTypeInfoCStyleCastExpr(Context,
2807 Context->getPointerType(ConstIdT),
2808 CK_BitCast,
2809 ArrayLiteralME);
2810
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002811 // Synthesize a call to objc_msgSend().
2812 SmallVector<Expr*, 32> MsgExprs;
2813 SmallVector<Expr*, 4> ClsExprs;
2814 QualType argType = Context->getPointerType(Context->CharTy);
2815 QualType expType = Exp->getType();
2816
2817 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2818 ObjCInterfaceDecl *Class =
2819 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2820
2821 IdentifierInfo *clsName = Class->getIdentifier();
2822 ClsExprs.push_back(StringLiteral::Create(*Context,
2823 clsName->getName(),
2824 StringLiteral::Ascii, false,
2825 argType, SourceLocation()));
2826 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2827 &ClsExprs[0],
2828 ClsExprs.size(),
2829 StartLoc, EndLoc);
2830 MsgExprs.push_back(Cls);
2831
2832 // Create a call to sel_registerName("arrayWithObjects:count:").
2833 // it will be the 2nd argument.
2834 SmallVector<Expr*, 4> SelExprs;
2835 ObjCMethodDecl *ArrayMethod = Exp->getArrayWithObjectsMethod();
2836 SelExprs.push_back(StringLiteral::Create(*Context,
2837 ArrayMethod->getSelector().getAsString(),
2838 StringLiteral::Ascii, false,
2839 argType, SourceLocation()));
2840 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2841 &SelExprs[0], SelExprs.size(),
2842 StartLoc, EndLoc);
2843 MsgExprs.push_back(SelExp);
2844
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002845 // (const id [])objects
2846 MsgExprs.push_back(ArrayLiteralObjects);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002847
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002848 // (NSUInteger)cnt
2849 Expr *cnt = IntegerLiteral::Create(*Context,
2850 llvm::APInt(UnsignedIntSize, NumElements),
2851 Context->UnsignedIntTy, SourceLocation());
2852 MsgExprs.push_back(cnt);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002853
2854
2855 SmallVector<QualType, 4> ArgTypes;
2856 ArgTypes.push_back(Context->getObjCIdType());
2857 ArgTypes.push_back(Context->getObjCSelType());
2858 for (ObjCMethodDecl::param_iterator PI = ArrayMethod->param_begin(),
2859 E = ArrayMethod->param_end(); PI != E; ++PI)
2860 ArgTypes.push_back((*PI)->getType());
2861
2862 QualType returnType = Exp->getType();
2863 // Get the type, we will need to reference it in a couple spots.
2864 QualType msgSendType = MsgSendFlavor->getType();
2865
2866 // Create a reference to the objc_msgSend() declaration.
2867 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2868 VK_LValue, SourceLocation());
2869
2870 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2871 Context->getPointerType(Context->VoidTy),
2872 CK_BitCast, DRE);
2873
2874 // Now do the "normal" pointer to function cast.
2875 QualType castType =
Jordan Rosebea522f2013-03-08 21:51:21 +00002876 getSimpleFunctionType(returnType, ArgTypes, ArrayMethod->isVariadic());
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002877 castType = Context->getPointerType(castType);
2878 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2879 cast);
2880
2881 // Don't forget the parens to enforce the proper binding.
2882 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2883
2884 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002885 CallExpr *CE = new (Context) CallExpr(*Context, PE, MsgExprs,
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002886 FT->getResultType(), VK_RValue,
2887 EndLoc);
2888 ReplaceStmt(Exp, CE);
2889 return CE;
2890}
2891
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002892Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp) {
2893 // synthesize declaration of helper functions needed in this routine.
2894 if (!SelGetUidFunctionDecl)
2895 SynthSelGetUidFunctionDecl();
2896 // use objc_msgSend() for all.
2897 if (!MsgSendFunctionDecl)
2898 SynthMsgSendFunctionDecl();
2899 if (!GetClassFunctionDecl)
2900 SynthGetClassFunctionDecl();
2901
2902 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2903 SourceLocation StartLoc = Exp->getLocStart();
2904 SourceLocation EndLoc = Exp->getLocEnd();
2905
2906 // Build the expression: __NSContainer_literal(int, ...).arr
2907 QualType IntQT = Context->IntTy;
2908 QualType NSDictFType =
Jordan Rosebea522f2013-03-08 21:51:21 +00002909 getSimpleFunctionType(Context->VoidTy, IntQT, true);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002910 std::string NSDictFName("__NSContainer_literal");
2911 FunctionDecl *NSDictFD = SynthBlockInitFunctionDecl(NSDictFName);
2912 DeclRefExpr *NSDictDRE =
2913 new (Context) DeclRefExpr(NSDictFD, false, NSDictFType, VK_RValue,
2914 SourceLocation());
2915
2916 SmallVector<Expr*, 16> KeyExprs;
2917 SmallVector<Expr*, 16> ValueExprs;
2918
2919 unsigned NumElements = Exp->getNumElements();
2920 unsigned UnsignedIntSize =
2921 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2922 Expr *count = IntegerLiteral::Create(*Context,
2923 llvm::APInt(UnsignedIntSize, NumElements),
2924 Context->UnsignedIntTy, SourceLocation());
2925 KeyExprs.push_back(count);
2926 ValueExprs.push_back(count);
2927 for (unsigned i = 0; i < NumElements; i++) {
2928 ObjCDictionaryElement Element = Exp->getKeyValueElement(i);
2929 KeyExprs.push_back(Element.Key);
2930 ValueExprs.push_back(Element.Value);
2931 }
2932
2933 // (const id [])objects
2934 Expr *NSValueCallExpr =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002935 new (Context) CallExpr(*Context, NSDictDRE, ValueExprs,
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002936 NSDictFType, VK_LValue, SourceLocation());
2937
2938 FieldDecl *ARRFD = FieldDecl::Create(*Context, 0, SourceLocation(),
2939 SourceLocation(),
2940 &Context->Idents.get("arr"),
2941 Context->getPointerType(Context->VoidPtrTy), 0,
2942 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00002943 ICIS_NoInit);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002944 MemberExpr *DictLiteralValueME =
2945 new (Context) MemberExpr(NSValueCallExpr, false, ARRFD,
2946 SourceLocation(),
2947 ARRFD->getType(), VK_LValue,
2948 OK_Ordinary);
2949 QualType ConstIdT = Context->getObjCIdType().withConst();
2950 CStyleCastExpr * DictValueObjects =
2951 NoTypeInfoCStyleCastExpr(Context,
2952 Context->getPointerType(ConstIdT),
2953 CK_BitCast,
2954 DictLiteralValueME);
2955 // (const id <NSCopying> [])keys
2956 Expr *NSKeyCallExpr =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002957 new (Context) CallExpr(*Context, NSDictDRE, KeyExprs,
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002958 NSDictFType, VK_LValue, SourceLocation());
2959
2960 MemberExpr *DictLiteralKeyME =
2961 new (Context) MemberExpr(NSKeyCallExpr, false, ARRFD,
2962 SourceLocation(),
2963 ARRFD->getType(), VK_LValue,
2964 OK_Ordinary);
2965
2966 CStyleCastExpr * DictKeyObjects =
2967 NoTypeInfoCStyleCastExpr(Context,
2968 Context->getPointerType(ConstIdT),
2969 CK_BitCast,
2970 DictLiteralKeyME);
2971
2972
2973
2974 // Synthesize a call to objc_msgSend().
2975 SmallVector<Expr*, 32> MsgExprs;
2976 SmallVector<Expr*, 4> ClsExprs;
2977 QualType argType = Context->getPointerType(Context->CharTy);
2978 QualType expType = Exp->getType();
2979
2980 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2981 ObjCInterfaceDecl *Class =
2982 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2983
2984 IdentifierInfo *clsName = Class->getIdentifier();
2985 ClsExprs.push_back(StringLiteral::Create(*Context,
2986 clsName->getName(),
2987 StringLiteral::Ascii, false,
2988 argType, SourceLocation()));
2989 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2990 &ClsExprs[0],
2991 ClsExprs.size(),
2992 StartLoc, EndLoc);
2993 MsgExprs.push_back(Cls);
2994
2995 // Create a call to sel_registerName("arrayWithObjects:count:").
2996 // it will be the 2nd argument.
2997 SmallVector<Expr*, 4> SelExprs;
2998 ObjCMethodDecl *DictMethod = Exp->getDictWithObjectsMethod();
2999 SelExprs.push_back(StringLiteral::Create(*Context,
3000 DictMethod->getSelector().getAsString(),
3001 StringLiteral::Ascii, false,
3002 argType, SourceLocation()));
3003 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
3004 &SelExprs[0], SelExprs.size(),
3005 StartLoc, EndLoc);
3006 MsgExprs.push_back(SelExp);
3007
3008 // (const id [])objects
3009 MsgExprs.push_back(DictValueObjects);
3010
3011 // (const id <NSCopying> [])keys
3012 MsgExprs.push_back(DictKeyObjects);
3013
3014 // (NSUInteger)cnt
3015 Expr *cnt = IntegerLiteral::Create(*Context,
3016 llvm::APInt(UnsignedIntSize, NumElements),
3017 Context->UnsignedIntTy, SourceLocation());
3018 MsgExprs.push_back(cnt);
3019
3020
3021 SmallVector<QualType, 8> ArgTypes;
3022 ArgTypes.push_back(Context->getObjCIdType());
3023 ArgTypes.push_back(Context->getObjCSelType());
3024 for (ObjCMethodDecl::param_iterator PI = DictMethod->param_begin(),
3025 E = DictMethod->param_end(); PI != E; ++PI) {
3026 QualType T = (*PI)->getType();
3027 if (const PointerType* PT = T->getAs<PointerType>()) {
3028 QualType PointeeTy = PT->getPointeeType();
3029 convertToUnqualifiedObjCType(PointeeTy);
3030 T = Context->getPointerType(PointeeTy);
3031 }
3032 ArgTypes.push_back(T);
3033 }
3034
3035 QualType returnType = Exp->getType();
3036 // Get the type, we will need to reference it in a couple spots.
3037 QualType msgSendType = MsgSendFlavor->getType();
3038
3039 // Create a reference to the objc_msgSend() declaration.
3040 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
3041 VK_LValue, SourceLocation());
3042
3043 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
3044 Context->getPointerType(Context->VoidTy),
3045 CK_BitCast, DRE);
3046
3047 // Now do the "normal" pointer to function cast.
3048 QualType castType =
Jordan Rosebea522f2013-03-08 21:51:21 +00003049 getSimpleFunctionType(returnType, ArgTypes, DictMethod->isVariadic());
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00003050 castType = Context->getPointerType(castType);
3051 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3052 cast);
3053
3054 // Don't forget the parens to enforce the proper binding.
3055 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3056
3057 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003058 CallExpr *CE = new (Context) CallExpr(*Context, PE, MsgExprs,
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00003059 FT->getResultType(), VK_RValue,
3060 EndLoc);
3061 ReplaceStmt(Exp, CE);
3062 return CE;
3063}
3064
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003065// struct __rw_objc_super {
3066// struct objc_object *object; struct objc_object *superClass;
3067// };
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003068QualType RewriteModernObjC::getSuperStructType() {
3069 if (!SuperStructDecl) {
3070 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3071 SourceLocation(), SourceLocation(),
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003072 &Context->Idents.get("__rw_objc_super"));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003073 QualType FieldTypes[2];
3074
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003075 // struct objc_object *object;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003076 FieldTypes[0] = Context->getObjCIdType();
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003077 // struct objc_object *superClass;
3078 FieldTypes[1] = Context->getObjCIdType();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003079
3080 // Create fields
3081 for (unsigned i = 0; i < 2; ++i) {
3082 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
3083 SourceLocation(),
3084 SourceLocation(), 0,
3085 FieldTypes[i], 0,
3086 /*BitWidth=*/0,
3087 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00003088 ICIS_NoInit));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003089 }
3090
3091 SuperStructDecl->completeDefinition();
3092 }
3093 return Context->getTagDeclType(SuperStructDecl);
3094}
3095
3096QualType RewriteModernObjC::getConstantStringStructType() {
3097 if (!ConstantStringDecl) {
3098 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3099 SourceLocation(), SourceLocation(),
3100 &Context->Idents.get("__NSConstantStringImpl"));
3101 QualType FieldTypes[4];
3102
3103 // struct objc_object *receiver;
3104 FieldTypes[0] = Context->getObjCIdType();
3105 // int flags;
3106 FieldTypes[1] = Context->IntTy;
3107 // char *str;
3108 FieldTypes[2] = Context->getPointerType(Context->CharTy);
3109 // long length;
3110 FieldTypes[3] = Context->LongTy;
3111
3112 // Create fields
3113 for (unsigned i = 0; i < 4; ++i) {
3114 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
3115 ConstantStringDecl,
3116 SourceLocation(),
3117 SourceLocation(), 0,
3118 FieldTypes[i], 0,
3119 /*BitWidth=*/0,
3120 /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00003121 ICIS_NoInit));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003122 }
3123
3124 ConstantStringDecl->completeDefinition();
3125 }
3126 return Context->getTagDeclType(ConstantStringDecl);
3127}
3128
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003129/// getFunctionSourceLocation - returns start location of a function
3130/// definition. Complication arises when function has declared as
3131/// extern "C" or extern "C" {...}
3132static SourceLocation getFunctionSourceLocation (RewriteModernObjC &R,
3133 FunctionDecl *FD) {
3134 if (FD->isExternC() && !FD->isMain()) {
3135 const DeclContext *DC = FD->getDeclContext();
3136 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3137 // if it is extern "C" {...}, return function decl's own location.
3138 if (!LSD->getRBraceLoc().isValid())
3139 return LSD->getExternLoc();
3140 }
Rafael Espindolad2615cc2013-04-03 19:27:57 +00003141 if (FD->getStorageClass() != SC_None)
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003142 R.RewriteBlockLiteralFunctionDecl(FD);
3143 return FD->getTypeSpecStartLoc();
3144}
3145
Fariborz Jahanian96205962012-11-06 17:30:23 +00003146void RewriteModernObjC::RewriteLineDirective(const Decl *D) {
3147
3148 SourceLocation Location = D->getLocation();
3149
Fariborz Jahanianada71912013-02-08 00:27:34 +00003150 if (Location.isFileID() && GenerateLineInfo) {
Fariborz Jahanian3b45ca92012-11-07 18:15:53 +00003151 std::string LineString("\n#line ");
Fariborz Jahanian96205962012-11-06 17:30:23 +00003152 PresumedLoc PLoc = SM->getPresumedLoc(Location);
3153 LineString += utostr(PLoc.getLine());
3154 LineString += " \"";
NAKAMURA Takumiba529a92012-11-06 22:45:31 +00003155 LineString += Lexer::Stringify(PLoc.getFilename());
Fariborz Jahanian96205962012-11-06 17:30:23 +00003156 if (isa<ObjCMethodDecl>(D))
3157 LineString += "\"";
3158 else LineString += "\"\n";
3159
3160 Location = D->getLocStart();
3161 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3162 if (FD->isExternC() && !FD->isMain()) {
3163 const DeclContext *DC = FD->getDeclContext();
3164 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3165 // if it is extern "C" {...}, return function decl's own location.
3166 if (!LSD->getRBraceLoc().isValid())
3167 Location = LSD->getExternLoc();
3168 }
3169 }
3170 InsertText(Location, LineString);
3171 }
3172}
3173
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003174/// SynthMsgSendStretCallExpr - This routine translates message expression
3175/// into a call to objc_msgSend_stret() entry point. Tricky part is that
3176/// nil check on receiver must be performed before calling objc_msgSend_stret.
3177/// MsgSendStretFlavor - function declaration objc_msgSend_stret(...)
3178/// msgSendType - function type of objc_msgSend_stret(...)
3179/// returnType - Result type of the method being synthesized.
3180/// ArgTypes - type of the arguments passed to objc_msgSend_stret, starting with receiver type.
3181/// MsgExprs - list of argument expressions being passed to objc_msgSend_stret,
3182/// starting with receiver.
3183/// Method - Method being rewritten.
3184Expr *RewriteModernObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003185 QualType returnType,
3186 SmallVectorImpl<QualType> &ArgTypes,
3187 SmallVectorImpl<Expr*> &MsgExprs,
3188 ObjCMethodDecl *Method) {
3189 // Now do the "normal" pointer to function cast.
Jordan Rosebea522f2013-03-08 21:51:21 +00003190 QualType castType = getSimpleFunctionType(returnType, ArgTypes,
3191 Method ? Method->isVariadic()
3192 : false);
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003193 castType = Context->getPointerType(castType);
3194
3195 // build type for containing the objc_msgSend_stret object.
3196 static unsigned stretCount=0;
3197 std::string name = "__Stret"; name += utostr(stretCount);
Fariborz Jahanian2ca5af22012-07-25 21:48:36 +00003198 std::string str =
3199 "extern \"C\" void * __cdecl memset(void *_Dst, int _Val, size_t _Size);\n";
Fariborz Jahanian426bb9c2013-09-09 19:59:59 +00003200 str += "namespace {\n";
Fariborz Jahanian2ca5af22012-07-25 21:48:36 +00003201 str += "struct "; str += name;
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003202 str += " {\n\t";
3203 str += name;
3204 str += "(id receiver, SEL sel";
3205 for (unsigned i = 2; i < ArgTypes.size(); i++) {
Fariborz Jahanian6734ec42012-06-29 19:55:46 +00003206 std::string ArgName = "arg"; ArgName += utostr(i);
3207 ArgTypes[i].getAsStringInternal(ArgName, Context->getPrintingPolicy());
3208 str += ", "; str += ArgName;
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003209 }
3210 // could be vararg.
3211 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
Fariborz Jahanian6734ec42012-06-29 19:55:46 +00003212 std::string ArgName = "arg"; ArgName += utostr(i);
3213 MsgExprs[i]->getType().getAsStringInternal(ArgName,
3214 Context->getPrintingPolicy());
3215 str += ", "; str += ArgName;
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003216 }
3217
3218 str += ") {\n";
Fariborz Jahanian426bb9c2013-09-09 19:59:59 +00003219 str += "\t unsigned size = sizeof(";
3220 str += returnType.getAsString(Context->getPrintingPolicy()); str += ");\n";
3221
3222 str += "\t if (size == 1 || size == 2 || size == 4 || size == 8)\n";
3223
3224 str += "\t s = (("; str += castType.getAsString(Context->getPrintingPolicy());
3225 str += ")(void *)objc_msgSend)(receiver, sel";
3226 for (unsigned i = 2; i < ArgTypes.size(); i++) {
3227 str += ", arg"; str += utostr(i);
3228 }
3229 // could be vararg.
3230 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3231 str += ", arg"; str += utostr(i);
3232 }
3233 str+= ");\n";
3234
3235 str += "\t else if (receiver == 0)\n";
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003236 str += "\t memset((void*)&s, 0, sizeof(s));\n";
3237 str += "\t else\n";
Fariborz Jahanian426bb9c2013-09-09 19:59:59 +00003238
3239
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003240 str += "\t s = (("; str += castType.getAsString(Context->getPrintingPolicy());
3241 str += ")(void *)objc_msgSend_stret)(receiver, sel";
3242 for (unsigned i = 2; i < ArgTypes.size(); i++) {
3243 str += ", arg"; str += utostr(i);
3244 }
3245 // could be vararg.
3246 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3247 str += ", arg"; str += utostr(i);
3248 }
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003249 str += ");\n";
Fariborz Jahanian426bb9c2013-09-09 19:59:59 +00003250
3251
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003252 str += "\t}\n";
3253 str += "\t"; str += returnType.getAsString(Context->getPrintingPolicy());
3254 str += " s;\n";
Fariborz Jahanian426bb9c2013-09-09 19:59:59 +00003255 str += "};\n};\n\n";
Fariborz Jahaniana6e5a6e2012-08-21 18:56:50 +00003256 SourceLocation FunLocStart;
3257 if (CurFunctionDef)
3258 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
3259 else {
3260 assert(CurMethodDef && "SynthMsgSendStretCallExpr - CurMethodDef is null");
3261 FunLocStart = CurMethodDef->getLocStart();
3262 }
3263
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003264 InsertText(FunLocStart, str);
3265 ++stretCount;
3266
3267 // AST for __Stretn(receiver, args).s;
3268 IdentifierInfo *ID = &Context->Idents.get(name);
3269 FunctionDecl *FD = FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
Chad Rosiere3b29882013-01-04 22:40:33 +00003270 SourceLocation(), ID, castType, 0,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00003271 SC_Extern, false, false);
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003272 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, castType, VK_RValue,
3273 SourceLocation());
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003274 CallExpr *STCE = new (Context) CallExpr(*Context, DRE, MsgExprs,
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003275 castType, VK_LValue, SourceLocation());
3276
3277 FieldDecl *FieldD = FieldDecl::Create(*Context, 0, SourceLocation(),
3278 SourceLocation(),
3279 &Context->Idents.get("s"),
3280 returnType, 0,
3281 /*BitWidth=*/0, /*Mutable=*/true,
3282 ICIS_NoInit);
3283 MemberExpr *ME = new (Context) MemberExpr(STCE, false, FieldD, SourceLocation(),
3284 FieldD->getType(), VK_LValue,
3285 OK_Ordinary);
3286
3287 return ME;
3288}
3289
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003290Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
3291 SourceLocation StartLoc,
3292 SourceLocation EndLoc) {
3293 if (!SelGetUidFunctionDecl)
3294 SynthSelGetUidFunctionDecl();
3295 if (!MsgSendFunctionDecl)
3296 SynthMsgSendFunctionDecl();
3297 if (!MsgSendSuperFunctionDecl)
3298 SynthMsgSendSuperFunctionDecl();
3299 if (!MsgSendStretFunctionDecl)
3300 SynthMsgSendStretFunctionDecl();
3301 if (!MsgSendSuperStretFunctionDecl)
3302 SynthMsgSendSuperStretFunctionDecl();
3303 if (!MsgSendFpretFunctionDecl)
3304 SynthMsgSendFpretFunctionDecl();
3305 if (!GetClassFunctionDecl)
3306 SynthGetClassFunctionDecl();
3307 if (!GetSuperClassFunctionDecl)
3308 SynthGetSuperClassFunctionDecl();
3309 if (!GetMetaClassFunctionDecl)
3310 SynthGetMetaClassFunctionDecl();
3311
3312 // default to objc_msgSend().
3313 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
3314 // May need to use objc_msgSend_stret() as well.
3315 FunctionDecl *MsgSendStretFlavor = 0;
3316 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
3317 QualType resultType = mDecl->getResultType();
3318 if (resultType->isRecordType())
3319 MsgSendStretFlavor = MsgSendStretFunctionDecl;
3320 else if (resultType->isRealFloatingType())
3321 MsgSendFlavor = MsgSendFpretFunctionDecl;
3322 }
3323
3324 // Synthesize a call to objc_msgSend().
3325 SmallVector<Expr*, 8> MsgExprs;
3326 switch (Exp->getReceiverKind()) {
3327 case ObjCMessageExpr::SuperClass: {
3328 MsgSendFlavor = MsgSendSuperFunctionDecl;
3329 if (MsgSendStretFlavor)
3330 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3331 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3332
3333 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3334
3335 SmallVector<Expr*, 4> InitExprs;
3336
3337 // set the receiver to self, the first argument to all methods.
3338 InitExprs.push_back(
3339 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3340 CK_BitCast,
3341 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00003342 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003343 Context->getObjCIdType(),
3344 VK_RValue,
3345 SourceLocation()))
3346 ); // set the 'receiver'.
3347
3348 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3349 SmallVector<Expr*, 8> ClsExprs;
3350 QualType argType = Context->getPointerType(Context->CharTy);
3351 ClsExprs.push_back(StringLiteral::Create(*Context,
3352 ClassDecl->getIdentifier()->getName(),
3353 StringLiteral::Ascii, false,
3354 argType, SourceLocation()));
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003355 // (Class)objc_getClass("CurrentClass")
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003356 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
3357 &ClsExprs[0],
3358 ClsExprs.size(),
3359 StartLoc,
3360 EndLoc);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003361 ClsExprs.clear();
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003362 ClsExprs.push_back(Cls);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003363 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3364 &ClsExprs[0], ClsExprs.size(),
3365 StartLoc, EndLoc);
3366
3367 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3368 // To turn off a warning, type-cast to 'id'
3369 InitExprs.push_back( // set 'super class', using class_getSuperclass().
3370 NoTypeInfoCStyleCastExpr(Context,
3371 Context->getObjCIdType(),
3372 CK_BitCast, Cls));
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003373 // struct __rw_objc_super
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003374 QualType superType = getSuperStructType();
3375 Expr *SuperRep;
3376
3377 if (LangOpts.MicrosoftExt) {
Benjamin Kramere5753592013-09-09 14:48:42 +00003378 SynthSuperConstructorFunctionDecl();
3379 // Simulate a constructor call...
3380 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperConstructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00003381 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003382 SourceLocation());
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003383 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003384 superType, VK_LValue,
3385 SourceLocation());
3386 // The code for super is a little tricky to prevent collision with
3387 // the structure definition in the header. The rewriter has it's own
3388 // internal definition (__rw_objc_super) that is uses. This is why
3389 // we need the cast below. For example:
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003390 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003391 //
3392 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3393 Context->getPointerType(SuperRep->getType()),
3394 VK_RValue, OK_Ordinary,
3395 SourceLocation());
3396 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3397 Context->getPointerType(superType),
3398 CK_BitCast, SuperRep);
3399 } else {
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003400 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003401 InitListExpr *ILE =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003402 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003403 SourceLocation());
3404 TypeSourceInfo *superTInfo
3405 = Context->getTrivialTypeSourceInfo(superType);
3406 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3407 superType, VK_LValue,
3408 ILE, false);
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003409 // struct __rw_objc_super *
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003410 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3411 Context->getPointerType(SuperRep->getType()),
3412 VK_RValue, OK_Ordinary,
3413 SourceLocation());
3414 }
3415 MsgExprs.push_back(SuperRep);
3416 break;
3417 }
3418
3419 case ObjCMessageExpr::Class: {
3420 SmallVector<Expr*, 8> ClsExprs;
3421 QualType argType = Context->getPointerType(Context->CharTy);
3422 ObjCInterfaceDecl *Class
3423 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
3424 IdentifierInfo *clsName = Class->getIdentifier();
3425 ClsExprs.push_back(StringLiteral::Create(*Context,
3426 clsName->getName(),
3427 StringLiteral::Ascii, false,
3428 argType, SourceLocation()));
3429 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3430 &ClsExprs[0],
3431 ClsExprs.size(),
3432 StartLoc, EndLoc);
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003433 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
3434 Context->getObjCIdType(),
3435 CK_BitCast, Cls);
3436 MsgExprs.push_back(ArgExpr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003437 break;
3438 }
3439
3440 case ObjCMessageExpr::SuperInstance:{
3441 MsgSendFlavor = MsgSendSuperFunctionDecl;
3442 if (MsgSendStretFlavor)
3443 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3444 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3445 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3446 SmallVector<Expr*, 4> InitExprs;
3447
3448 InitExprs.push_back(
3449 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3450 CK_BitCast,
3451 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00003452 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003453 Context->getObjCIdType(),
3454 VK_RValue, SourceLocation()))
3455 ); // set the 'receiver'.
3456
3457 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3458 SmallVector<Expr*, 8> ClsExprs;
3459 QualType argType = Context->getPointerType(Context->CharTy);
3460 ClsExprs.push_back(StringLiteral::Create(*Context,
3461 ClassDecl->getIdentifier()->getName(),
3462 StringLiteral::Ascii, false, argType,
3463 SourceLocation()));
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003464 // (Class)objc_getClass("CurrentClass")
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003465 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3466 &ClsExprs[0],
3467 ClsExprs.size(),
3468 StartLoc, EndLoc);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003469 ClsExprs.clear();
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003470 ClsExprs.push_back(Cls);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003471 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3472 &ClsExprs[0], ClsExprs.size(),
3473 StartLoc, EndLoc);
3474
3475 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3476 // To turn off a warning, type-cast to 'id'
3477 InitExprs.push_back(
3478 // set 'super class', using class_getSuperclass().
3479 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3480 CK_BitCast, Cls));
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003481 // struct __rw_objc_super
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003482 QualType superType = getSuperStructType();
3483 Expr *SuperRep;
3484
3485 if (LangOpts.MicrosoftExt) {
Benjamin Kramere5753592013-09-09 14:48:42 +00003486 SynthSuperConstructorFunctionDecl();
3487 // Simulate a constructor call...
3488 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperConstructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00003489 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003490 SourceLocation());
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003491 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003492 superType, VK_LValue, SourceLocation());
3493 // The code for super is a little tricky to prevent collision with
3494 // the structure definition in the header. The rewriter has it's own
3495 // internal definition (__rw_objc_super) that is uses. This is why
3496 // we need the cast below. For example:
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003497 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003498 //
3499 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3500 Context->getPointerType(SuperRep->getType()),
3501 VK_RValue, OK_Ordinary,
3502 SourceLocation());
3503 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3504 Context->getPointerType(superType),
3505 CK_BitCast, SuperRep);
3506 } else {
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003507 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003508 InitListExpr *ILE =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003509 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003510 SourceLocation());
3511 TypeSourceInfo *superTInfo
3512 = Context->getTrivialTypeSourceInfo(superType);
3513 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3514 superType, VK_RValue, ILE,
3515 false);
3516 }
3517 MsgExprs.push_back(SuperRep);
3518 break;
3519 }
3520
3521 case ObjCMessageExpr::Instance: {
3522 // Remove all type-casts because it may contain objc-style types; e.g.
3523 // Foo<Proto> *.
3524 Expr *recExpr = Exp->getInstanceReceiver();
3525 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
3526 recExpr = CE->getSubExpr();
3527 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
3528 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
3529 ? CK_BlockPointerToObjCPointerCast
3530 : CK_CPointerToObjCPointerCast;
3531
3532 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3533 CK, recExpr);
3534 MsgExprs.push_back(recExpr);
3535 break;
3536 }
3537 }
3538
3539 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
3540 SmallVector<Expr*, 8> SelExprs;
3541 QualType argType = Context->getPointerType(Context->CharTy);
3542 SelExprs.push_back(StringLiteral::Create(*Context,
3543 Exp->getSelector().getAsString(),
3544 StringLiteral::Ascii, false,
3545 argType, SourceLocation()));
3546 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
3547 &SelExprs[0], SelExprs.size(),
3548 StartLoc,
3549 EndLoc);
3550 MsgExprs.push_back(SelExp);
3551
3552 // Now push any user supplied arguments.
3553 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
3554 Expr *userExpr = Exp->getArg(i);
3555 // Make all implicit casts explicit...ICE comes in handy:-)
3556 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
3557 // Reuse the ICE type, it is exactly what the doctor ordered.
3558 QualType type = ICE->getType();
3559 if (needToScanForQualifiers(type))
3560 type = Context->getObjCIdType();
3561 // Make sure we convert "type (^)(...)" to "type (*)(...)".
3562 (void)convertBlockPointerToFunctionPointer(type);
3563 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
3564 CastKind CK;
3565 if (SubExpr->getType()->isIntegralType(*Context) &&
3566 type->isBooleanType()) {
3567 CK = CK_IntegralToBoolean;
3568 } else if (type->isObjCObjectPointerType()) {
3569 if (SubExpr->getType()->isBlockPointerType()) {
3570 CK = CK_BlockPointerToObjCPointerCast;
3571 } else if (SubExpr->getType()->isPointerType()) {
3572 CK = CK_CPointerToObjCPointerCast;
3573 } else {
3574 CK = CK_BitCast;
3575 }
3576 } else {
3577 CK = CK_BitCast;
3578 }
3579
3580 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
3581 }
3582 // Make id<P...> cast into an 'id' cast.
3583 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
3584 if (CE->getType()->isObjCQualifiedIdType()) {
3585 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
3586 userExpr = CE->getSubExpr();
3587 CastKind CK;
3588 if (userExpr->getType()->isIntegralType(*Context)) {
3589 CK = CK_IntegralToPointer;
3590 } else if (userExpr->getType()->isBlockPointerType()) {
3591 CK = CK_BlockPointerToObjCPointerCast;
3592 } else if (userExpr->getType()->isPointerType()) {
3593 CK = CK_CPointerToObjCPointerCast;
3594 } else {
3595 CK = CK_BitCast;
3596 }
3597 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3598 CK, userExpr);
3599 }
3600 }
3601 MsgExprs.push_back(userExpr);
3602 // We've transferred the ownership to MsgExprs. For now, we *don't* null
3603 // out the argument in the original expression (since we aren't deleting
3604 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
3605 //Exp->setArg(i, 0);
3606 }
3607 // Generate the funky cast.
3608 CastExpr *cast;
3609 SmallVector<QualType, 8> ArgTypes;
3610 QualType returnType;
3611
3612 // Push 'id' and 'SEL', the 2 implicit arguments.
3613 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3614 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3615 else
3616 ArgTypes.push_back(Context->getObjCIdType());
3617 ArgTypes.push_back(Context->getObjCSelType());
3618 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
3619 // Push any user argument types.
3620 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
3621 E = OMD->param_end(); PI != E; ++PI) {
3622 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
3623 ? Context->getObjCIdType()
3624 : (*PI)->getType();
3625 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3626 (void)convertBlockPointerToFunctionPointer(t);
3627 ArgTypes.push_back(t);
3628 }
3629 returnType = Exp->getType();
3630 convertToUnqualifiedObjCType(returnType);
3631 (void)convertBlockPointerToFunctionPointer(returnType);
3632 } else {
3633 returnType = Context->getObjCIdType();
3634 }
3635 // Get the type, we will need to reference it in a couple spots.
3636 QualType msgSendType = MsgSendFlavor->getType();
3637
3638 // Create a reference to the objc_msgSend() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00003639 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003640 VK_LValue, SourceLocation());
3641
3642 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
3643 // If we don't do this cast, we get the following bizarre warning/note:
3644 // xx.m:13: warning: function called through a non-compatible type
3645 // xx.m:13: note: if this code is reached, the program will abort
3646 cast = NoTypeInfoCStyleCastExpr(Context,
3647 Context->getPointerType(Context->VoidTy),
3648 CK_BitCast, DRE);
3649
3650 // Now do the "normal" pointer to function cast.
Jordan Rosebea522f2013-03-08 21:51:21 +00003651 // If we don't have a method decl, force a variadic cast.
3652 const ObjCMethodDecl *MD = Exp->getMethodDecl();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003653 QualType castType =
Jordan Rosebea522f2013-03-08 21:51:21 +00003654 getSimpleFunctionType(returnType, ArgTypes, MD ? MD->isVariadic() : true);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003655 castType = Context->getPointerType(castType);
3656 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3657 cast);
3658
3659 // Don't forget the parens to enforce the proper binding.
3660 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3661
3662 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003663 CallExpr *CE = new (Context) CallExpr(*Context, PE, MsgExprs,
3664 FT->getResultType(), VK_RValue, EndLoc);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003665 Stmt *ReplacingStmt = CE;
3666 if (MsgSendStretFlavor) {
3667 // We have the method which returns a struct/union. Must also generate
3668 // call to objc_msgSend_stret and hang both varieties on a conditional
3669 // expression which dictate which one to envoke depending on size of
3670 // method's return type.
3671
Fariborz Jahanian426bb9c2013-09-09 19:59:59 +00003672 Expr *STCE = SynthMsgSendStretCallExpr(MsgSendStretFlavor,
3673 returnType,
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003674 ArgTypes, MsgExprs,
3675 Exp->getMethodDecl());
Fariborz Jahanian426bb9c2013-09-09 19:59:59 +00003676 ReplacingStmt = STCE;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003677 }
3678 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3679 return ReplacingStmt;
3680}
3681
3682Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
3683 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3684 Exp->getLocEnd());
3685
3686 // Now do the actual rewrite.
3687 ReplaceStmt(Exp, ReplacingStmt);
3688
3689 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3690 return ReplacingStmt;
3691}
3692
3693// typedef struct objc_object Protocol;
3694QualType RewriteModernObjC::getProtocolType() {
3695 if (!ProtocolTypeDecl) {
3696 TypeSourceInfo *TInfo
3697 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3698 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
3699 SourceLocation(), SourceLocation(),
3700 &Context->Idents.get("Protocol"),
3701 TInfo);
3702 }
3703 return Context->getTypeDeclType(ProtocolTypeDecl);
3704}
3705
3706/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3707/// a synthesized/forward data reference (to the protocol's metadata).
3708/// The forward references (and metadata) are generated in
3709/// RewriteModernObjC::HandleTranslationUnit().
3710Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00003711 std::string Name = "_OBJC_PROTOCOL_REFERENCE_$_" +
3712 Exp->getProtocol()->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003713 IdentifierInfo *ID = &Context->Idents.get(Name);
3714 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
3715 SourceLocation(), ID, getProtocolType(), 0,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00003716 SC_Extern);
John McCallf4b88a42012-03-10 09:33:50 +00003717 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
3718 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003719 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
3720 Context->getPointerType(DRE->getType()),
3721 VK_RValue, OK_Ordinary, SourceLocation());
3722 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
3723 CK_BitCast,
3724 DerefExpr);
3725 ReplaceStmt(Exp, castExpr);
3726 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3727 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3728 return castExpr;
3729
3730}
3731
3732bool RewriteModernObjC::BufferContainsPPDirectives(const char *startBuf,
3733 const char *endBuf) {
3734 while (startBuf < endBuf) {
3735 if (*startBuf == '#') {
3736 // Skip whitespace.
3737 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3738 ;
3739 if (!strncmp(startBuf, "if", strlen("if")) ||
3740 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3741 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3742 !strncmp(startBuf, "define", strlen("define")) ||
3743 !strncmp(startBuf, "undef", strlen("undef")) ||
3744 !strncmp(startBuf, "else", strlen("else")) ||
3745 !strncmp(startBuf, "elif", strlen("elif")) ||
3746 !strncmp(startBuf, "endif", strlen("endif")) ||
3747 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3748 !strncmp(startBuf, "include", strlen("include")) ||
3749 !strncmp(startBuf, "import", strlen("import")) ||
3750 !strncmp(startBuf, "include_next", strlen("include_next")))
3751 return true;
3752 }
3753 startBuf++;
3754 }
3755 return false;
3756}
3757
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003758/// IsTagDefinedInsideClass - This routine checks that a named tagged type
3759/// is defined inside an objective-c class. If so, it returns true.
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00003760bool RewriteModernObjC::IsTagDefinedInsideClass(ObjCContainerDecl *IDecl,
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003761 TagDecl *Tag,
3762 bool &IsNamedDefinition) {
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003763 if (!IDecl)
3764 return false;
3765 SourceLocation TagLocation;
3766 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) {
3767 RD = RD->getDefinition();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003768 if (!RD || !RD->getDeclName().getAsIdentifierInfo())
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003769 return false;
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003770 IsNamedDefinition = true;
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003771 TagLocation = RD->getLocation();
3772 return Context->getSourceManager().isBeforeInTranslationUnit(
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003773 IDecl->getLocation(), TagLocation);
3774 }
3775 if (EnumDecl *ED = dyn_cast<EnumDecl>(Tag)) {
3776 if (!ED || !ED->getDeclName().getAsIdentifierInfo())
3777 return false;
3778 IsNamedDefinition = true;
3779 TagLocation = ED->getLocation();
3780 return Context->getSourceManager().isBeforeInTranslationUnit(
3781 IDecl->getLocation(), TagLocation);
3782
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003783 }
3784 return false;
3785}
3786
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003787/// RewriteObjCFieldDeclType - This routine rewrites a type into the buffer.
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003788/// It handles elaborated types, as well as enum types in the process.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003789bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type,
3790 std::string &Result) {
Fariborz Jahanianf5eac482012-05-02 17:34:59 +00003791 if (isa<TypedefType>(Type)) {
3792 Result += "\t";
3793 return false;
3794 }
3795
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003796 if (Type->isArrayType()) {
3797 QualType ElemTy = Context->getBaseElementType(Type);
3798 return RewriteObjCFieldDeclType(ElemTy, Result);
3799 }
3800 else if (Type->isRecordType()) {
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003801 RecordDecl *RD = Type->getAs<RecordType>()->getDecl();
3802 if (RD->isCompleteDefinition()) {
3803 if (RD->isStruct())
3804 Result += "\n\tstruct ";
3805 else if (RD->isUnion())
3806 Result += "\n\tunion ";
3807 else
3808 assert(false && "class not allowed as an ivar type");
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003809
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003810 Result += RD->getName();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003811 if (GlobalDefinedTags.count(RD)) {
3812 // struct/union is defined globally, use it.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003813 Result += " ";
3814 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003815 }
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003816 Result += " {\n";
3817 for (RecordDecl::field_iterator i = RD->field_begin(),
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003818 e = RD->field_end(); i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00003819 FieldDecl *FD = *i;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003820 RewriteObjCFieldDecl(FD, Result);
3821 }
3822 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003823 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003824 }
3825 }
3826 else if (Type->isEnumeralType()) {
3827 EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3828 if (ED->isCompleteDefinition()) {
3829 Result += "\n\tenum ";
3830 Result += ED->getName();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003831 if (GlobalDefinedTags.count(ED)) {
3832 // Enum is globall defined, use it.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003833 Result += " ";
3834 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003835 }
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003836
3837 Result += " {\n";
3838 for (EnumDecl::enumerator_iterator EC = ED->enumerator_begin(),
3839 ECEnd = ED->enumerator_end(); EC != ECEnd; ++EC) {
3840 Result += "\t"; Result += EC->getName(); Result += " = ";
3841 llvm::APSInt Val = EC->getInitVal();
3842 Result += Val.toString(10);
3843 Result += ",\n";
3844 }
3845 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003846 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003847 }
3848 }
3849
3850 Result += "\t";
3851 convertObjCTypeToCStyleType(Type);
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003852 return false;
3853}
3854
3855
3856/// RewriteObjCFieldDecl - This routine rewrites a field into the buffer.
3857/// It handles elaborated types, as well as enum types in the process.
3858void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl,
3859 std::string &Result) {
3860 QualType Type = fieldDecl->getType();
3861 std::string Name = fieldDecl->getNameAsString();
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003862
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003863 bool EleboratedType = RewriteObjCFieldDeclType(Type, Result);
3864 if (!EleboratedType)
3865 Type.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003866 Result += Name;
3867 if (fieldDecl->isBitField()) {
3868 Result += " : "; Result += utostr(fieldDecl->getBitWidthValue(*Context));
3869 }
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003870 else if (EleboratedType && Type->isArrayType()) {
Eli Friedman6febf122012-12-13 01:43:21 +00003871 const ArrayType *AT = Context->getAsArrayType(Type);
3872 do {
3873 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003874 Result += "[";
3875 llvm::APInt Dim = CAT->getSize();
3876 Result += utostr(Dim.getZExtValue());
3877 Result += "]";
3878 }
Eli Friedman6febf122012-12-13 01:43:21 +00003879 AT = Context->getAsArrayType(AT->getElementType());
3880 } while (AT);
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003881 }
3882
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003883 Result += ";\n";
3884}
3885
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003886/// RewriteLocallyDefinedNamedAggregates - This routine rewrites locally defined
3887/// named aggregate types into the input buffer.
3888void RewriteModernObjC::RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
3889 std::string &Result) {
3890 QualType Type = fieldDecl->getType();
Fariborz Jahanianf5eac482012-05-02 17:34:59 +00003891 if (isa<TypedefType>(Type))
3892 return;
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003893 if (Type->isArrayType())
3894 Type = Context->getBaseElementType(Type);
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00003895 ObjCContainerDecl *IDecl =
3896 dyn_cast<ObjCContainerDecl>(fieldDecl->getDeclContext());
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003897
3898 TagDecl *TD = 0;
3899 if (Type->isRecordType()) {
3900 TD = Type->getAs<RecordType>()->getDecl();
3901 }
3902 else if (Type->isEnumeralType()) {
3903 TD = Type->getAs<EnumType>()->getDecl();
3904 }
3905
3906 if (TD) {
3907 if (GlobalDefinedTags.count(TD))
3908 return;
3909
3910 bool IsNamedDefinition = false;
3911 if (IsTagDefinedInsideClass(IDecl, TD, IsNamedDefinition)) {
3912 RewriteObjCFieldDeclType(Type, Result);
3913 Result += ";";
3914 }
3915 if (IsNamedDefinition)
3916 GlobalDefinedTags.insert(TD);
3917 }
3918
3919}
3920
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00003921unsigned RewriteModernObjC::ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV) {
3922 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3923 if (ObjCInterefaceHasBitfieldGroups.count(CDecl)) {
3924 return IvarGroupNumber[IV];
3925 }
3926 unsigned GroupNo = 0;
3927 SmallVector<const ObjCIvarDecl *, 8> IVars;
3928 for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3929 IVD; IVD = IVD->getNextIvar())
3930 IVars.push_back(IVD);
3931
3932 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3933 if (IVars[i]->isBitField()) {
3934 IvarGroupNumber[IVars[i++]] = ++GroupNo;
3935 while (i < e && IVars[i]->isBitField())
3936 IvarGroupNumber[IVars[i++]] = GroupNo;
3937 if (i < e)
3938 --i;
3939 }
3940
3941 ObjCInterefaceHasBitfieldGroups.insert(CDecl);
3942 return IvarGroupNumber[IV];
3943}
3944
3945QualType RewriteModernObjC::SynthesizeBitfieldGroupStructType(
3946 ObjCIvarDecl *IV,
3947 SmallVectorImpl<ObjCIvarDecl *> &IVars) {
3948 std::string StructTagName;
3949 ObjCIvarBitfieldGroupType(IV, StructTagName);
3950 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct,
3951 Context->getTranslationUnitDecl(),
3952 SourceLocation(), SourceLocation(),
3953 &Context->Idents.get(StructTagName));
3954 for (unsigned i=0, e = IVars.size(); i < e; i++) {
3955 ObjCIvarDecl *Ivar = IVars[i];
3956 RD->addDecl(FieldDecl::Create(*Context, RD, SourceLocation(), SourceLocation(),
3957 &Context->Idents.get(Ivar->getName()),
3958 Ivar->getType(),
3959 0, /*Expr *BW */Ivar->getBitWidth(), false,
3960 ICIS_NoInit));
3961 }
3962 RD->completeDefinition();
3963 return Context->getTagDeclType(RD);
3964}
3965
3966QualType RewriteModernObjC::GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl *IV) {
3967 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3968 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3969 std::pair<const ObjCInterfaceDecl*, unsigned> tuple = std::make_pair(CDecl, GroupNo);
3970 if (GroupRecordType.count(tuple))
3971 return GroupRecordType[tuple];
3972
3973 SmallVector<ObjCIvarDecl *, 8> IVars;
3974 for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3975 IVD; IVD = IVD->getNextIvar()) {
3976 if (IVD->isBitField())
3977 IVars.push_back(const_cast<ObjCIvarDecl *>(IVD));
3978 else {
3979 if (!IVars.empty()) {
3980 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
3981 // Generate the struct type for this group of bitfield ivars.
3982 GroupRecordType[std::make_pair(CDecl, GroupNo)] =
3983 SynthesizeBitfieldGroupStructType(IVars[0], IVars);
3984 IVars.clear();
3985 }
3986 }
3987 }
3988 if (!IVars.empty()) {
3989 // Do the last one.
3990 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
3991 GroupRecordType[std::make_pair(CDecl, GroupNo)] =
3992 SynthesizeBitfieldGroupStructType(IVars[0], IVars);
3993 }
3994 QualType RetQT = GroupRecordType[tuple];
3995 assert(!RetQT.isNull() && "GetGroupRecordTypeForObjCIvarBitfield struct type is NULL");
3996
3997 return RetQT;
3998}
3999
4000/// ObjCIvarBitfieldGroupDecl - Names field decl. for ivar bitfield group.
4001/// Name would be: classname__GRBF_n where n is the group number for this ivar.
4002void RewriteModernObjC::ObjCIvarBitfieldGroupDecl(ObjCIvarDecl *IV,
4003 std::string &Result) {
4004 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
4005 Result += CDecl->getName();
4006 Result += "__GRBF_";
4007 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
4008 Result += utostr(GroupNo);
4009 return;
4010}
4011
4012/// ObjCIvarBitfieldGroupType - Names struct type for ivar bitfield group.
4013/// Name of the struct would be: classname__T_n where n is the group number for
4014/// this ivar.
4015void RewriteModernObjC::ObjCIvarBitfieldGroupType(ObjCIvarDecl *IV,
4016 std::string &Result) {
4017 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
4018 Result += CDecl->getName();
4019 Result += "__T_";
4020 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
4021 Result += utostr(GroupNo);
4022 return;
4023}
4024
4025/// ObjCIvarBitfieldGroupOffset - Names symbol for ivar bitfield group field offset.
4026/// Name would be: OBJC_IVAR_$_classname__GRBF_n where n is the group number for
4027/// this ivar.
4028void RewriteModernObjC::ObjCIvarBitfieldGroupOffset(ObjCIvarDecl *IV,
4029 std::string &Result) {
4030 Result += "OBJC_IVAR_$_";
4031 ObjCIvarBitfieldGroupDecl(IV, Result);
4032}
4033
4034#define SKIP_BITFIELDS(IX, ENDIX, VEC) { \
4035 while ((IX < ENDIX) && VEC[IX]->isBitField()) \
4036 ++IX; \
4037 if (IX < ENDIX) \
4038 --IX; \
4039}
4040
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004041/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
4042/// an objective-c class with ivars.
4043void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
4044 std::string &Result) {
4045 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
4046 assert(CDecl->getName() != "" &&
4047 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004048 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00004049 SmallVector<ObjCIvarDecl *, 8> IVars;
4050 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00004051 IVD; IVD = IVD->getNextIvar())
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00004052 IVars.push_back(IVD);
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00004053
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004054 SourceLocation LocStart = CDecl->getLocStart();
4055 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00004056
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004057 const char *startBuf = SM->getCharacterData(LocStart);
4058 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00004059
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004060 // If no ivars and no root or if its root, directly or indirectly,
4061 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00004062 if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) &&
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004063 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
4064 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
4065 ReplaceText(LocStart, endBuf-startBuf, Result);
4066 return;
4067 }
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00004068
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00004069 // Insert named struct/union definitions inside class to
4070 // outer scope. This follows semantics of locally defined
4071 // struct/unions in objective-c classes.
4072 for (unsigned i = 0, e = IVars.size(); i < e; i++)
4073 RewriteLocallyDefinedNamedAggregates(IVars[i], Result);
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00004074
4075 // Insert named structs which are syntheized to group ivar bitfields
4076 // to outer scope as well.
4077 for (unsigned i = 0, e = IVars.size(); i < e; i++)
4078 if (IVars[i]->isBitField()) {
4079 ObjCIvarDecl *IV = IVars[i];
4080 QualType QT = GetGroupRecordTypeForObjCIvarBitfield(IV);
4081 RewriteObjCFieldDeclType(QT, Result);
4082 Result += ";";
4083 // skip over ivar bitfields in this group.
4084 SKIP_BITFIELDS(i , e, IVars);
4085 }
4086
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004087 Result += "\nstruct ";
4088 Result += CDecl->getNameAsString();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00004089 Result += "_IMPL {\n";
4090
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00004091 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00004092 Result += "\tstruct "; Result += RCDecl->getNameAsString();
4093 Result += "_IMPL "; Result += RCDecl->getNameAsString();
4094 Result += "_IVARS;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004095 }
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00004096
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00004097 for (unsigned i = 0, e = IVars.size(); i < e; i++) {
4098 if (IVars[i]->isBitField()) {
4099 ObjCIvarDecl *IV = IVars[i];
4100 Result += "\tstruct ";
4101 ObjCIvarBitfieldGroupType(IV, Result); Result += " ";
4102 ObjCIvarBitfieldGroupDecl(IV, Result); Result += ";\n";
4103 // skip over ivar bitfields in this group.
4104 SKIP_BITFIELDS(i , e, IVars);
4105 }
4106 else
4107 RewriteObjCFieldDecl(IVars[i], Result);
4108 }
Fariborz Jahanian0b17b9a2012-02-12 21:36:23 +00004109
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00004110 Result += "};\n";
4111 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
4112 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00004113 // Mark this struct as having been generated.
4114 if (!ObjCSynthesizedStructs.insert(CDecl))
4115 llvm_unreachable("struct already synthesize- RewriteObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004116}
4117
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00004118/// RewriteIvarOffsetSymbols - Rewrite ivar offset symbols of those ivars which
4119/// have been referenced in an ivar access expression.
4120void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
4121 std::string &Result) {
4122 // write out ivar offset symbols which have been referenced in an ivar
4123 // access expression.
4124 llvm::SmallPtrSet<ObjCIvarDecl *, 8> Ivars = ReferencedIvars[CDecl];
4125 if (Ivars.empty())
4126 return;
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00004127
4128 llvm::DenseSet<std::pair<const ObjCInterfaceDecl*, unsigned> > GroupSymbolOutput;
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00004129 for (llvm::SmallPtrSet<ObjCIvarDecl *, 8>::iterator i = Ivars.begin(),
4130 e = Ivars.end(); i != e; i++) {
4131 ObjCIvarDecl *IvarDecl = (*i);
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00004132 const ObjCInterfaceDecl *IDecl = IvarDecl->getContainingInterface();
4133 unsigned GroupNo = 0;
4134 if (IvarDecl->isBitField()) {
4135 GroupNo = ObjCIvarBitfieldGroupNo(IvarDecl);
4136 if (GroupSymbolOutput.count(std::make_pair(IDecl, GroupNo)))
4137 continue;
4138 }
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00004139 Result += "\n";
4140 if (LangOpts.MicrosoftExt)
4141 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00004142 Result += "extern \"C\" ";
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00004143 if (LangOpts.MicrosoftExt &&
4144 IvarDecl->getAccessControl() != ObjCIvarDecl::Private &&
Fariborz Jahanian297976d2012-03-29 17:51:09 +00004145 IvarDecl->getAccessControl() != ObjCIvarDecl::Package)
4146 Result += "__declspec(dllimport) ";
4147
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00004148 Result += "unsigned long ";
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00004149 if (IvarDecl->isBitField()) {
4150 ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
4151 GroupSymbolOutput.insert(std::make_pair(IDecl, GroupNo));
4152 }
4153 else
4154 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00004155 Result += ";";
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00004156 }
4157}
4158
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004159//===----------------------------------------------------------------------===//
4160// Meta Data Emission
4161//===----------------------------------------------------------------------===//
4162
4163
4164/// RewriteImplementations - This routine rewrites all method implementations
4165/// and emits meta-data.
4166
4167void RewriteModernObjC::RewriteImplementations() {
4168 int ClsDefCount = ClassImplementation.size();
4169 int CatDefCount = CategoryImplementation.size();
4170
4171 // Rewrite implemented methods
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00004172 for (int i = 0; i < ClsDefCount; i++) {
4173 ObjCImplementationDecl *OIMP = ClassImplementation[i];
4174 ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
4175 if (CDecl->isImplicitInterfaceDecl())
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00004176 assert(false &&
4177 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00004178 RewriteImplementationDecl(OIMP);
4179 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004180
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00004181 for (int i = 0; i < CatDefCount; i++) {
4182 ObjCCategoryImplDecl *CIMP = CategoryImplementation[i];
4183 ObjCInterfaceDecl *CDecl = CIMP->getClassInterface();
4184 if (CDecl->isImplicitInterfaceDecl())
4185 assert(false &&
4186 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00004187 RewriteImplementationDecl(CIMP);
4188 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004189}
4190
4191void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
4192 const std::string &Name,
4193 ValueDecl *VD, bool def) {
4194 assert(BlockByRefDeclNo.count(VD) &&
4195 "RewriteByRefString: ByRef decl missing");
4196 if (def)
4197 ResultStr += "struct ";
4198 ResultStr += "__Block_byref_" + Name +
4199 "_" + utostr(BlockByRefDeclNo[VD]) ;
4200}
4201
4202static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
4203 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4204 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
4205 return false;
4206}
4207
4208std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
4209 StringRef funcName,
4210 std::string Tag) {
4211 const FunctionType *AFT = CE->getFunctionType();
4212 QualType RT = AFT->getResultType();
4213 std::string StructRef = "struct " + Tag;
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00004214 SourceLocation BlockLoc = CE->getExprLoc();
4215 std::string S;
4216 ConvertSourceLocationToLineDirective(BlockLoc, S);
4217
4218 S += "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
4219 funcName.str() + "_block_func_" + utostr(i);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004220
4221 BlockDecl *BD = CE->getBlockDecl();
4222
4223 if (isa<FunctionNoProtoType>(AFT)) {
4224 // No user-supplied arguments. Still need to pass in a pointer to the
4225 // block (to reference imported block decl refs).
4226 S += "(" + StructRef + " *__cself)";
4227 } else if (BD->param_empty()) {
4228 S += "(" + StructRef + " *__cself)";
4229 } else {
4230 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
4231 assert(FT && "SynthesizeBlockFunc: No function proto");
4232 S += '(';
4233 // first add the implicit argument.
4234 S += StructRef + " *__cself, ";
4235 std::string ParamStr;
4236 for (BlockDecl::param_iterator AI = BD->param_begin(),
4237 E = BD->param_end(); AI != E; ++AI) {
4238 if (AI != BD->param_begin()) S += ", ";
4239 ParamStr = (*AI)->getNameAsString();
4240 QualType QT = (*AI)->getType();
Fariborz Jahanian2610f902012-03-27 16:42:20 +00004241 (void)convertBlockPointerToFunctionPointer(QT);
4242 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004243 S += ParamStr;
4244 }
4245 if (FT->isVariadic()) {
4246 if (!BD->param_empty()) S += ", ";
4247 S += "...";
4248 }
4249 S += ')';
4250 }
4251 S += " {\n";
4252
4253 // Create local declarations to avoid rewriting all closure decl ref exprs.
4254 // First, emit a declaration for all "by ref" decls.
Craig Topper09d19ef2013-07-04 03:08:24 +00004255 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004256 E = BlockByRefDecls.end(); I != E; ++I) {
4257 S += " ";
4258 std::string Name = (*I)->getNameAsString();
4259 std::string TypeString;
4260 RewriteByRefString(TypeString, Name, (*I));
4261 TypeString += " *";
4262 Name = TypeString + Name;
4263 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
4264 }
4265 // Next, emit a declaration for all "by copy" declarations.
Craig Topper09d19ef2013-07-04 03:08:24 +00004266 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004267 E = BlockByCopyDecls.end(); I != E; ++I) {
4268 S += " ";
4269 // Handle nested closure invocation. For example:
4270 //
4271 // void (^myImportedClosure)(void);
4272 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
4273 //
4274 // void (^anotherClosure)(void);
4275 // anotherClosure = ^(void) {
4276 // myImportedClosure(); // import and invoke the closure
4277 // };
4278 //
4279 if (isTopLevelBlockPointerType((*I)->getType())) {
4280 RewriteBlockPointerTypeVariable(S, (*I));
4281 S += " = (";
4282 RewriteBlockPointerType(S, (*I)->getType());
4283 S += ")";
4284 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4285 }
4286 else {
4287 std::string Name = (*I)->getNameAsString();
4288 QualType QT = (*I)->getType();
4289 if (HasLocalVariableExternalStorage(*I))
4290 QT = Context->getPointerType(QT);
4291 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
4292 S += Name + " = __cself->" +
4293 (*I)->getNameAsString() + "; // bound by copy\n";
4294 }
4295 }
4296 std::string RewrittenStr = RewrittenBlockExprs[CE];
4297 const char *cstr = RewrittenStr.c_str();
4298 while (*cstr++ != '{') ;
4299 S += cstr;
4300 S += "\n";
4301 return S;
4302}
4303
4304std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
4305 StringRef funcName,
4306 std::string Tag) {
4307 std::string StructRef = "struct " + Tag;
4308 std::string S = "static void __";
4309
4310 S += funcName;
4311 S += "_block_copy_" + utostr(i);
4312 S += "(" + StructRef;
4313 S += "*dst, " + StructRef;
4314 S += "*src) {";
4315 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
4316 E = ImportedBlockDecls.end(); I != E; ++I) {
4317 ValueDecl *VD = (*I);
4318 S += "_Block_object_assign((void*)&dst->";
4319 S += (*I)->getNameAsString();
4320 S += ", (void*)src->";
4321 S += (*I)->getNameAsString();
4322 if (BlockByRefDeclsPtrSet.count((*I)))
4323 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4324 else if (VD->getType()->isBlockPointerType())
4325 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4326 else
4327 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4328 }
4329 S += "}\n";
4330
4331 S += "\nstatic void __";
4332 S += funcName;
4333 S += "_block_dispose_" + utostr(i);
4334 S += "(" + StructRef;
4335 S += "*src) {";
4336 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
4337 E = ImportedBlockDecls.end(); I != E; ++I) {
4338 ValueDecl *VD = (*I);
4339 S += "_Block_object_dispose((void*)src->";
4340 S += (*I)->getNameAsString();
4341 if (BlockByRefDeclsPtrSet.count((*I)))
4342 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4343 else if (VD->getType()->isBlockPointerType())
4344 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4345 else
4346 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4347 }
4348 S += "}\n";
4349 return S;
4350}
4351
4352std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4353 std::string Desc) {
4354 std::string S = "\nstruct " + Tag;
4355 std::string Constructor = " " + Tag;
4356
4357 S += " {\n struct __block_impl impl;\n";
4358 S += " struct " + Desc;
4359 S += "* Desc;\n";
4360
4361 Constructor += "(void *fp, "; // Invoke function pointer.
4362 Constructor += "struct " + Desc; // Descriptor pointer.
4363 Constructor += " *desc";
4364
4365 if (BlockDeclRefs.size()) {
4366 // Output all "by copy" declarations.
Craig Topper09d19ef2013-07-04 03:08:24 +00004367 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004368 E = BlockByCopyDecls.end(); I != E; ++I) {
4369 S += " ";
4370 std::string FieldName = (*I)->getNameAsString();
4371 std::string ArgName = "_" + FieldName;
4372 // Handle nested closure invocation. For example:
4373 //
4374 // void (^myImportedBlock)(void);
4375 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
4376 //
4377 // void (^anotherBlock)(void);
4378 // anotherBlock = ^(void) {
4379 // myImportedBlock(); // import and invoke the closure
4380 // };
4381 //
4382 if (isTopLevelBlockPointerType((*I)->getType())) {
4383 S += "struct __block_impl *";
4384 Constructor += ", void *" + ArgName;
4385 } else {
4386 QualType QT = (*I)->getType();
4387 if (HasLocalVariableExternalStorage(*I))
4388 QT = Context->getPointerType(QT);
4389 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
4390 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
4391 Constructor += ", " + ArgName;
4392 }
4393 S += FieldName + ";\n";
4394 }
4395 // Output all "by ref" declarations.
Craig Topper09d19ef2013-07-04 03:08:24 +00004396 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004397 E = BlockByRefDecls.end(); I != E; ++I) {
4398 S += " ";
4399 std::string FieldName = (*I)->getNameAsString();
4400 std::string ArgName = "_" + FieldName;
4401 {
4402 std::string TypeString;
4403 RewriteByRefString(TypeString, FieldName, (*I));
4404 TypeString += " *";
4405 FieldName = TypeString + FieldName;
4406 ArgName = TypeString + ArgName;
4407 Constructor += ", " + ArgName;
4408 }
4409 S += FieldName + "; // by ref\n";
4410 }
4411 // Finish writing the constructor.
4412 Constructor += ", int flags=0)";
4413 // Initialize all "by copy" arguments.
4414 bool firsTime = true;
Craig Topper09d19ef2013-07-04 03:08:24 +00004415 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004416 E = BlockByCopyDecls.end(); I != E; ++I) {
4417 std::string Name = (*I)->getNameAsString();
4418 if (firsTime) {
4419 Constructor += " : ";
4420 firsTime = false;
4421 }
4422 else
4423 Constructor += ", ";
4424 if (isTopLevelBlockPointerType((*I)->getType()))
4425 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4426 else
4427 Constructor += Name + "(_" + Name + ")";
4428 }
4429 // Initialize all "by ref" arguments.
Craig Topper09d19ef2013-07-04 03:08:24 +00004430 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004431 E = BlockByRefDecls.end(); I != E; ++I) {
4432 std::string Name = (*I)->getNameAsString();
4433 if (firsTime) {
4434 Constructor += " : ";
4435 firsTime = false;
4436 }
4437 else
4438 Constructor += ", ";
4439 Constructor += Name + "(_" + Name + "->__forwarding)";
4440 }
4441
4442 Constructor += " {\n";
4443 if (GlobalVarDecl)
4444 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4445 else
4446 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4447 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4448
4449 Constructor += " Desc = desc;\n";
4450 } else {
4451 // Finish writing the constructor.
4452 Constructor += ", int flags=0) {\n";
4453 if (GlobalVarDecl)
4454 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4455 else
4456 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4457 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4458 Constructor += " Desc = desc;\n";
4459 }
4460 Constructor += " ";
4461 Constructor += "}\n";
4462 S += Constructor;
4463 S += "};\n";
4464 return S;
4465}
4466
4467std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag,
4468 std::string ImplTag, int i,
4469 StringRef FunName,
4470 unsigned hasCopy) {
4471 std::string S = "\nstatic struct " + DescTag;
4472
Fariborz Jahanian8b08adb2012-05-03 21:44:12 +00004473 S += " {\n size_t reserved;\n";
4474 S += " size_t Block_size;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004475 if (hasCopy) {
4476 S += " void (*copy)(struct ";
4477 S += ImplTag; S += "*, struct ";
4478 S += ImplTag; S += "*);\n";
4479
4480 S += " void (*dispose)(struct ";
4481 S += ImplTag; S += "*);\n";
4482 }
4483 S += "} ";
4484
4485 S += DescTag + "_DATA = { 0, sizeof(struct ";
4486 S += ImplTag + ")";
4487 if (hasCopy) {
4488 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4489 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
4490 }
4491 S += "};\n";
4492 return S;
4493}
4494
4495void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
4496 StringRef FunName) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004497 bool RewriteSC = (GlobalVarDecl &&
4498 !Blocks.empty() &&
4499 GlobalVarDecl->getStorageClass() == SC_Static &&
4500 GlobalVarDecl->getType().getCVRQualifiers());
4501 if (RewriteSC) {
4502 std::string SC(" void __");
4503 SC += GlobalVarDecl->getNameAsString();
4504 SC += "() {}";
4505 InsertText(FunLocStart, SC);
4506 }
4507
4508 // Insert closures that were part of the function.
4509 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4510 CollectBlockDeclRefInfo(Blocks[i]);
4511 // Need to copy-in the inner copied-in variables not actually used in this
4512 // block.
4513 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
John McCallf4b88a42012-03-10 09:33:50 +00004514 DeclRefExpr *Exp = InnerDeclRefs[count++];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004515 ValueDecl *VD = Exp->getDecl();
4516 BlockDeclRefs.push_back(Exp);
John McCallf4b88a42012-03-10 09:33:50 +00004517 if (!VD->hasAttr<BlocksAttr>()) {
4518 if (!BlockByCopyDeclsPtrSet.count(VD)) {
4519 BlockByCopyDeclsPtrSet.insert(VD);
4520 BlockByCopyDecls.push_back(VD);
4521 }
4522 continue;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004523 }
John McCallf4b88a42012-03-10 09:33:50 +00004524
4525 if (!BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004526 BlockByRefDeclsPtrSet.insert(VD);
4527 BlockByRefDecls.push_back(VD);
4528 }
John McCallf4b88a42012-03-10 09:33:50 +00004529
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004530 // imported objects in the inner blocks not used in the outer
4531 // blocks must be copied/disposed in the outer block as well.
John McCallf4b88a42012-03-10 09:33:50 +00004532 if (VD->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004533 VD->getType()->isBlockPointerType())
4534 ImportedBlockDecls.insert(VD);
4535 }
4536
4537 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4538 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
4539
4540 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
4541
4542 InsertText(FunLocStart, CI);
4543
4544 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
4545
4546 InsertText(FunLocStart, CF);
4547
4548 if (ImportedBlockDecls.size()) {
4549 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
4550 InsertText(FunLocStart, HF);
4551 }
4552 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4553 ImportedBlockDecls.size() > 0);
4554 InsertText(FunLocStart, BD);
4555
4556 BlockDeclRefs.clear();
4557 BlockByRefDecls.clear();
4558 BlockByRefDeclsPtrSet.clear();
4559 BlockByCopyDecls.clear();
4560 BlockByCopyDeclsPtrSet.clear();
4561 ImportedBlockDecls.clear();
4562 }
4563 if (RewriteSC) {
4564 // Must insert any 'const/volatile/static here. Since it has been
4565 // removed as result of rewriting of block literals.
4566 std::string SC;
4567 if (GlobalVarDecl->getStorageClass() == SC_Static)
4568 SC = "static ";
4569 if (GlobalVarDecl->getType().isConstQualified())
4570 SC += "const ";
4571 if (GlobalVarDecl->getType().isVolatileQualified())
4572 SC += "volatile ";
4573 if (GlobalVarDecl->getType().isRestrictQualified())
4574 SC += "restrict ";
4575 InsertText(FunLocStart, SC);
4576 }
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004577 if (GlobalConstructionExp) {
4578 // extra fancy dance for global literal expression.
4579
4580 // Always the latest block expression on the block stack.
4581 std::string Tag = "__";
4582 Tag += FunName;
4583 Tag += "_block_impl_";
4584 Tag += utostr(Blocks.size()-1);
4585 std::string globalBuf = "static ";
4586 globalBuf += Tag; globalBuf += " ";
4587 std::string SStr;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004588
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004589 llvm::raw_string_ostream constructorExprBuf(SStr);
Richard Smithd1420c62012-08-16 03:56:14 +00004590 GlobalConstructionExp->printPretty(constructorExprBuf, 0,
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004591 PrintingPolicy(LangOpts));
4592 globalBuf += constructorExprBuf.str();
4593 globalBuf += ";\n";
4594 InsertText(FunLocStart, globalBuf);
4595 GlobalConstructionExp = 0;
4596 }
4597
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004598 Blocks.clear();
4599 InnerDeclRefsCount.clear();
4600 InnerDeclRefs.clear();
4601 RewrittenBlockExprs.clear();
4602}
4603
4604void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
Fariborz Jahanian04189532012-04-25 17:56:48 +00004605 SourceLocation FunLocStart =
4606 (!Blocks.empty()) ? getFunctionSourceLocation(*this, FD)
4607 : FD->getTypeSpecStartLoc();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004608 StringRef FuncName = FD->getName();
4609
4610 SynthesizeBlockLiterals(FunLocStart, FuncName);
4611}
4612
4613static void BuildUniqueMethodName(std::string &Name,
4614 ObjCMethodDecl *MD) {
4615 ObjCInterfaceDecl *IFace = MD->getClassInterface();
4616 Name = IFace->getName();
4617 Name += "__" + MD->getSelector().getAsString();
4618 // Convert colons to underscores.
4619 std::string::size_type loc = 0;
4620 while ((loc = Name.find(":", loc)) != std::string::npos)
4621 Name.replace(loc, 1, "_");
4622}
4623
4624void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
4625 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4626 //SourceLocation FunLocStart = MD->getLocStart();
4627 SourceLocation FunLocStart = MD->getLocStart();
4628 std::string FuncName;
4629 BuildUniqueMethodName(FuncName, MD);
4630 SynthesizeBlockLiterals(FunLocStart, FuncName);
4631}
4632
4633void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
4634 for (Stmt::child_range CI = S->children(); CI; ++CI)
4635 if (*CI) {
4636 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4637 GetBlockDeclRefExprs(CBE->getBody());
4638 else
4639 GetBlockDeclRefExprs(*CI);
4640 }
4641 // Handle specific things.
Fariborz Jahanian0e976812012-04-16 23:00:57 +00004642 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4643 if (DRE->refersToEnclosingLocal()) {
4644 // FIXME: Handle enums.
4645 if (!isa<FunctionDecl>(DRE->getDecl()))
4646 BlockDeclRefs.push_back(DRE);
4647 if (HasLocalVariableExternalStorage(DRE->getDecl()))
4648 BlockDeclRefs.push_back(DRE);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004649 }
Fariborz Jahanian0e976812012-04-16 23:00:57 +00004650 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004651
4652 return;
4653}
4654
Craig Topper6b9240e2013-07-05 19:34:19 +00004655void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
4656 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004657 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
4658 for (Stmt::child_range CI = S->children(); CI; ++CI)
4659 if (*CI) {
4660 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
4661 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
4662 GetInnerBlockDeclRefExprs(CBE->getBody(),
4663 InnerBlockDeclRefs,
4664 InnerContexts);
4665 }
4666 else
4667 GetInnerBlockDeclRefExprs(*CI,
4668 InnerBlockDeclRefs,
4669 InnerContexts);
4670
4671 }
4672 // Handle specific things.
John McCallf4b88a42012-03-10 09:33:50 +00004673 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4674 if (DRE->refersToEnclosingLocal()) {
4675 if (!isa<FunctionDecl>(DRE->getDecl()) &&
4676 !InnerContexts.count(DRE->getDecl()->getDeclContext()))
4677 InnerBlockDeclRefs.push_back(DRE);
4678 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
4679 if (Var->isFunctionOrMethodVarDecl())
4680 ImportedLocalExternalDecls.insert(Var);
4681 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004682 }
4683
4684 return;
4685}
4686
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004687/// convertObjCTypeToCStyleType - This routine converts such objc types
4688/// as qualified objects, and blocks to their closest c/c++ types that
4689/// it can. It returns true if input type was modified.
4690bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
4691 QualType oldT = T;
4692 convertBlockPointerToFunctionPointer(T);
4693 if (T->isFunctionPointerType()) {
4694 QualType PointeeTy;
4695 if (const PointerType* PT = T->getAs<PointerType>()) {
4696 PointeeTy = PT->getPointeeType();
4697 if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
4698 T = convertFunctionTypeOfBlocks(FT);
4699 T = Context->getPointerType(T);
4700 }
4701 }
4702 }
4703
4704 convertToUnqualifiedObjCType(T);
4705 return T != oldT;
4706}
4707
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004708/// convertFunctionTypeOfBlocks - This routine converts a function type
4709/// whose result type may be a block pointer or whose argument type(s)
4710/// might be block pointers to an equivalent function type replacing
4711/// all block pointers to function pointers.
4712QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4713 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4714 // FTP will be null for closures that don't take arguments.
4715 // Generate a funky cast.
4716 SmallVector<QualType, 8> ArgTypes;
4717 QualType Res = FT->getResultType();
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004718 bool modified = convertObjCTypeToCStyleType(Res);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004719
4720 if (FTP) {
4721 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4722 E = FTP->arg_type_end(); I && (I != E); ++I) {
4723 QualType t = *I;
4724 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004725 if (convertObjCTypeToCStyleType(t))
4726 modified = true;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004727 ArgTypes.push_back(t);
4728 }
4729 }
4730 QualType FuncType;
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004731 if (modified)
Jordan Rosebea522f2013-03-08 21:51:21 +00004732 FuncType = getSimpleFunctionType(Res, ArgTypes);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004733 else FuncType = QualType(FT, 0);
4734 return FuncType;
4735}
4736
4737Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
4738 // Navigate to relevant type information.
4739 const BlockPointerType *CPT = 0;
4740
4741 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
4742 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004743 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
4744 CPT = MExpr->getType()->getAs<BlockPointerType>();
4745 }
4746 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4747 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4748 }
4749 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4750 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4751 else if (const ConditionalOperator *CEXPR =
4752 dyn_cast<ConditionalOperator>(BlockExp)) {
4753 Expr *LHSExp = CEXPR->getLHS();
4754 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4755 Expr *RHSExp = CEXPR->getRHS();
4756 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4757 Expr *CONDExp = CEXPR->getCond();
4758 ConditionalOperator *CondExpr =
4759 new (Context) ConditionalOperator(CONDExp,
4760 SourceLocation(), cast<Expr>(LHSStmt),
4761 SourceLocation(), cast<Expr>(RHSStmt),
4762 Exp->getType(), VK_RValue, OK_Ordinary);
4763 return CondExpr;
4764 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4765 CPT = IRE->getType()->getAs<BlockPointerType>();
4766 } else if (const PseudoObjectExpr *POE
4767 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
4768 CPT = POE->getType()->castAs<BlockPointerType>();
4769 } else {
4770 assert(1 && "RewriteBlockClass: Bad type");
4771 }
4772 assert(CPT && "RewriteBlockClass: Bad type");
4773 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
4774 assert(FT && "RewriteBlockClass: Bad type");
4775 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4776 // FTP will be null for closures that don't take arguments.
4777
4778 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4779 SourceLocation(), SourceLocation(),
4780 &Context->Idents.get("__block_impl"));
4781 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
4782
4783 // Generate a funky cast.
4784 SmallVector<QualType, 8> ArgTypes;
4785
4786 // Push the block argument type.
4787 ArgTypes.push_back(PtrBlock);
4788 if (FTP) {
4789 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4790 E = FTP->arg_type_end(); I && (I != E); ++I) {
4791 QualType t = *I;
4792 // Make sure we convert "t (^)(...)" to "t (*)(...)".
4793 if (!convertBlockPointerToFunctionPointer(t))
4794 convertToUnqualifiedObjCType(t);
4795 ArgTypes.push_back(t);
4796 }
4797 }
4798 // Now do the pointer to function cast.
Jordan Rosebea522f2013-03-08 21:51:21 +00004799 QualType PtrToFuncCastType = getSimpleFunctionType(Exp->getType(), ArgTypes);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004800
4801 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
4802
4803 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4804 CK_BitCast,
4805 const_cast<Expr*>(BlockExp));
4806 // Don't forget the parens to enforce the proper binding.
4807 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4808 BlkCast);
4809 //PE->dump();
4810
4811 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4812 SourceLocation(),
4813 &Context->Idents.get("FuncPtr"),
4814 Context->VoidPtrTy, 0,
4815 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00004816 ICIS_NoInit);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004817 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4818 FD->getType(), VK_LValue,
4819 OK_Ordinary);
4820
4821
4822 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4823 CK_BitCast, ME);
4824 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
4825
4826 SmallVector<Expr*, 8> BlkExprs;
4827 // Add the implicit argument.
4828 BlkExprs.push_back(BlkCast);
4829 // Add the user arguments.
4830 for (CallExpr::arg_iterator I = Exp->arg_begin(),
4831 E = Exp->arg_end(); I != E; ++I) {
4832 BlkExprs.push_back(*I);
4833 }
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004834 CallExpr *CE = new (Context) CallExpr(*Context, PE, BlkExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004835 Exp->getType(), VK_RValue,
4836 SourceLocation());
4837 return CE;
4838}
4839
4840// We need to return the rewritten expression to handle cases where the
John McCallf4b88a42012-03-10 09:33:50 +00004841// DeclRefExpr is embedded in another expression being rewritten.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004842// For example:
4843//
4844// int main() {
4845// __block Foo *f;
4846// __block int i;
4847//
4848// void (^myblock)() = ^() {
John McCallf4b88a42012-03-10 09:33:50 +00004849// [f test]; // f is a DeclRefExpr embedded in a message (which is being rewritten).
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004850// i = 77;
4851// };
4852//}
John McCallf4b88a42012-03-10 09:33:50 +00004853Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004854 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
4855 // for each DeclRefExp where BYREFVAR is name of the variable.
John McCallf4b88a42012-03-10 09:33:50 +00004856 ValueDecl *VD = DeclRefExp->getDecl();
4857 bool isArrow = DeclRefExp->refersToEnclosingLocal();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004858
4859 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4860 SourceLocation(),
4861 &Context->Idents.get("__forwarding"),
4862 Context->VoidPtrTy, 0,
4863 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00004864 ICIS_NoInit);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004865 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4866 FD, SourceLocation(),
4867 FD->getType(), VK_LValue,
4868 OK_Ordinary);
4869
4870 StringRef Name = VD->getName();
4871 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
4872 &Context->Idents.get(Name),
4873 Context->VoidPtrTy, 0,
4874 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00004875 ICIS_NoInit);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004876 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
4877 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
4878
4879
4880
4881 // Need parens to enforce precedence.
4882 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
4883 DeclRefExp->getExprLoc(),
4884 ME);
4885 ReplaceStmt(DeclRefExp, PE);
4886 return PE;
4887}
4888
4889// Rewrites the imported local variable V with external storage
4890// (static, extern, etc.) as *V
4891//
4892Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4893 ValueDecl *VD = DRE->getDecl();
4894 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4895 if (!ImportedLocalExternalDecls.count(Var))
4896 return DRE;
4897 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4898 VK_LValue, OK_Ordinary,
4899 DRE->getLocation());
4900 // Need parens to enforce precedence.
4901 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4902 Exp);
4903 ReplaceStmt(DRE, PE);
4904 return PE;
4905}
4906
4907void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4908 SourceLocation LocStart = CE->getLParenLoc();
4909 SourceLocation LocEnd = CE->getRParenLoc();
4910
4911 // Need to avoid trying to rewrite synthesized casts.
4912 if (LocStart.isInvalid())
4913 return;
4914 // Need to avoid trying to rewrite casts contained in macros.
4915 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4916 return;
4917
4918 const char *startBuf = SM->getCharacterData(LocStart);
4919 const char *endBuf = SM->getCharacterData(LocEnd);
4920 QualType QT = CE->getType();
4921 const Type* TypePtr = QT->getAs<Type>();
4922 if (isa<TypeOfExprType>(TypePtr)) {
4923 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4924 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4925 std::string TypeAsString = "(";
4926 RewriteBlockPointerType(TypeAsString, QT);
4927 TypeAsString += ")";
4928 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
4929 return;
4930 }
4931 // advance the location to startArgList.
4932 const char *argPtr = startBuf;
4933
4934 while (*argPtr++ && (argPtr < endBuf)) {
4935 switch (*argPtr) {
4936 case '^':
4937 // Replace the '^' with '*'.
4938 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
4939 ReplaceText(LocStart, 1, "*");
4940 break;
4941 }
4942 }
4943 return;
4944}
4945
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00004946void RewriteModernObjC::RewriteImplicitCastObjCExpr(CastExpr *IC) {
4947 CastKind CastKind = IC->getCastKind();
Fariborz Jahanian43aa1c32012-04-16 22:14:01 +00004948 if (CastKind != CK_BlockPointerToObjCPointerCast &&
4949 CastKind != CK_AnyPointerToBlockPointerCast)
4950 return;
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00004951
Fariborz Jahanian43aa1c32012-04-16 22:14:01 +00004952 QualType QT = IC->getType();
4953 (void)convertBlockPointerToFunctionPointer(QT);
4954 std::string TypeString(QT.getAsString(Context->getPrintingPolicy()));
4955 std::string Str = "(";
4956 Str += TypeString;
4957 Str += ")";
4958 InsertText(IC->getSubExpr()->getLocStart(), &Str[0], Str.size());
4959
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00004960 return;
4961}
4962
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004963void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4964 SourceLocation DeclLoc = FD->getLocation();
4965 unsigned parenCount = 0;
4966
4967 // We have 1 or more arguments that have closure pointers.
4968 const char *startBuf = SM->getCharacterData(DeclLoc);
4969 const char *startArgList = strchr(startBuf, '(');
4970
4971 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
4972
4973 parenCount++;
4974 // advance the location to startArgList.
4975 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
4976 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
4977
4978 const char *argPtr = startArgList;
4979
4980 while (*argPtr++ && parenCount) {
4981 switch (*argPtr) {
4982 case '^':
4983 // Replace the '^' with '*'.
4984 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
4985 ReplaceText(DeclLoc, 1, "*");
4986 break;
4987 case '(':
4988 parenCount++;
4989 break;
4990 case ')':
4991 parenCount--;
4992 break;
4993 }
4994 }
4995 return;
4996}
4997
4998bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
4999 const FunctionProtoType *FTP;
5000 const PointerType *PT = QT->getAs<PointerType>();
5001 if (PT) {
5002 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
5003 } else {
5004 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
5005 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
5006 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
5007 }
5008 if (FTP) {
5009 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
5010 E = FTP->arg_type_end(); I != E; ++I)
5011 if (isTopLevelBlockPointerType(*I))
5012 return true;
5013 }
5014 return false;
5015}
5016
5017bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
5018 const FunctionProtoType *FTP;
5019 const PointerType *PT = QT->getAs<PointerType>();
5020 if (PT) {
5021 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
5022 } else {
5023 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
5024 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
5025 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
5026 }
5027 if (FTP) {
5028 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
5029 E = FTP->arg_type_end(); I != E; ++I) {
5030 if ((*I)->isObjCQualifiedIdType())
5031 return true;
5032 if ((*I)->isObjCObjectPointerType() &&
5033 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
5034 return true;
5035 }
5036
5037 }
5038 return false;
5039}
5040
5041void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
5042 const char *&RParen) {
5043 const char *argPtr = strchr(Name, '(');
5044 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
5045
5046 LParen = argPtr; // output the start.
5047 argPtr++; // skip past the left paren.
5048 unsigned parenCount = 1;
5049
5050 while (*argPtr && parenCount) {
5051 switch (*argPtr) {
5052 case '(': parenCount++; break;
5053 case ')': parenCount--; break;
5054 default: break;
5055 }
5056 if (parenCount) argPtr++;
5057 }
5058 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
5059 RParen = argPtr; // output the end
5060}
5061
5062void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
5063 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
5064 RewriteBlockPointerFunctionArgs(FD);
5065 return;
5066 }
5067 // Handle Variables and Typedefs.
5068 SourceLocation DeclLoc = ND->getLocation();
5069 QualType DeclT;
5070 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
5071 DeclT = VD->getType();
5072 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
5073 DeclT = TDD->getUnderlyingType();
5074 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
5075 DeclT = FD->getType();
5076 else
5077 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
5078
5079 const char *startBuf = SM->getCharacterData(DeclLoc);
5080 const char *endBuf = startBuf;
5081 // scan backward (from the decl location) for the end of the previous decl.
5082 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
5083 startBuf--;
5084 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
5085 std::string buf;
5086 unsigned OrigLength=0;
5087 // *startBuf != '^' if we are dealing with a pointer to function that
5088 // may take block argument types (which will be handled below).
5089 if (*startBuf == '^') {
5090 // Replace the '^' with '*', computing a negative offset.
5091 buf = '*';
5092 startBuf++;
5093 OrigLength++;
5094 }
5095 while (*startBuf != ')') {
5096 buf += *startBuf;
5097 startBuf++;
5098 OrigLength++;
5099 }
5100 buf += ')';
5101 OrigLength++;
5102
5103 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
5104 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
5105 // Replace the '^' with '*' for arguments.
5106 // Replace id<P> with id/*<>*/
5107 DeclLoc = ND->getLocation();
5108 startBuf = SM->getCharacterData(DeclLoc);
5109 const char *argListBegin, *argListEnd;
5110 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
5111 while (argListBegin < argListEnd) {
5112 if (*argListBegin == '^')
5113 buf += '*';
5114 else if (*argListBegin == '<') {
5115 buf += "/*";
5116 buf += *argListBegin++;
Dmitri Gribenko1ad23d62012-09-10 21:20:09 +00005117 OrigLength++;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005118 while (*argListBegin != '>') {
5119 buf += *argListBegin++;
5120 OrigLength++;
5121 }
5122 buf += *argListBegin;
5123 buf += "*/";
5124 }
5125 else
5126 buf += *argListBegin;
5127 argListBegin++;
5128 OrigLength++;
5129 }
5130 buf += ')';
5131 OrigLength++;
5132 }
5133 ReplaceText(Start, OrigLength, buf);
5134
5135 return;
5136}
5137
5138
5139/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
5140/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
5141/// struct Block_byref_id_object *src) {
5142/// _Block_object_assign (&_dest->object, _src->object,
5143/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5144/// [|BLOCK_FIELD_IS_WEAK]) // object
5145/// _Block_object_assign(&_dest->object, _src->object,
5146/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5147/// [|BLOCK_FIELD_IS_WEAK]) // block
5148/// }
5149/// And:
5150/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
5151/// _Block_object_dispose(_src->object,
5152/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5153/// [|BLOCK_FIELD_IS_WEAK]) // object
5154/// _Block_object_dispose(_src->object,
5155/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5156/// [|BLOCK_FIELD_IS_WEAK]) // block
5157/// }
5158
5159std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
5160 int flag) {
5161 std::string S;
5162 if (CopyDestroyCache.count(flag))
5163 return S;
5164 CopyDestroyCache.insert(flag);
5165 S = "static void __Block_byref_id_object_copy_";
5166 S += utostr(flag);
5167 S += "(void *dst, void *src) {\n";
5168
5169 // offset into the object pointer is computed as:
5170 // void * + void* + int + int + void* + void *
5171 unsigned IntSize =
5172 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5173 unsigned VoidPtrSize =
5174 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
5175
5176 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
5177 S += " _Block_object_assign((char*)dst + ";
5178 S += utostr(offset);
5179 S += ", *(void * *) ((char*)src + ";
5180 S += utostr(offset);
5181 S += "), ";
5182 S += utostr(flag);
5183 S += ");\n}\n";
5184
5185 S += "static void __Block_byref_id_object_dispose_";
5186 S += utostr(flag);
5187 S += "(void *src) {\n";
5188 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
5189 S += utostr(offset);
5190 S += "), ";
5191 S += utostr(flag);
5192 S += ");\n}\n";
5193 return S;
5194}
5195
5196/// RewriteByRefVar - For each __block typex ND variable this routine transforms
5197/// the declaration into:
5198/// struct __Block_byref_ND {
5199/// void *__isa; // NULL for everything except __weak pointers
5200/// struct __Block_byref_ND *__forwarding;
5201/// int32_t __flags;
5202/// int32_t __size;
5203/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
5204/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
5205/// typex ND;
5206/// };
5207///
5208/// It then replaces declaration of ND variable with:
5209/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
5210/// __size=sizeof(struct __Block_byref_ND),
5211/// ND=initializer-if-any};
5212///
5213///
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00005214void RewriteModernObjC::RewriteByRefVar(VarDecl *ND, bool firstDecl,
5215 bool lastDecl) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005216 int flag = 0;
5217 int isa = 0;
5218 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
5219 if (DeclLoc.isInvalid())
5220 // If type location is missing, it is because of missing type (a warning).
5221 // Use variable's location which is good for this case.
5222 DeclLoc = ND->getLocation();
5223 const char *startBuf = SM->getCharacterData(DeclLoc);
5224 SourceLocation X = ND->getLocEnd();
5225 X = SM->getExpansionLoc(X);
5226 const char *endBuf = SM->getCharacterData(X);
5227 std::string Name(ND->getNameAsString());
5228 std::string ByrefType;
5229 RewriteByRefString(ByrefType, Name, ND, true);
5230 ByrefType += " {\n";
5231 ByrefType += " void *__isa;\n";
5232 RewriteByRefString(ByrefType, Name, ND);
5233 ByrefType += " *__forwarding;\n";
5234 ByrefType += " int __flags;\n";
5235 ByrefType += " int __size;\n";
5236 // Add void *__Block_byref_id_object_copy;
5237 // void *__Block_byref_id_object_dispose; if needed.
5238 QualType Ty = ND->getType();
Fariborz Jahanianb15c8982012-11-28 23:12:17 +00005239 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty, ND);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005240 if (HasCopyAndDispose) {
5241 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
5242 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
5243 }
5244
5245 QualType T = Ty;
5246 (void)convertBlockPointerToFunctionPointer(T);
5247 T.getAsStringInternal(Name, Context->getPrintingPolicy());
5248
5249 ByrefType += " " + Name + ";\n";
5250 ByrefType += "};\n";
5251 // Insert this type in global scope. It is needed by helper function.
5252 SourceLocation FunLocStart;
5253 if (CurFunctionDef)
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00005254 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005255 else {
5256 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
5257 FunLocStart = CurMethodDef->getLocStart();
5258 }
5259 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian8247c4e2012-04-24 16:45:27 +00005260
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005261 if (Ty.isObjCGCWeak()) {
5262 flag |= BLOCK_FIELD_IS_WEAK;
5263 isa = 1;
5264 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005265 if (HasCopyAndDispose) {
5266 flag = BLOCK_BYREF_CALLER;
5267 QualType Ty = ND->getType();
5268 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
5269 if (Ty->isBlockPointerType())
5270 flag |= BLOCK_FIELD_IS_BLOCK;
5271 else
5272 flag |= BLOCK_FIELD_IS_OBJECT;
5273 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
5274 if (!HF.empty())
Fariborz Jahanian31c4a4b2013-02-07 22:50:40 +00005275 Preamble += HF;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005276 }
5277
5278 // struct __Block_byref_ND ND =
5279 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
5280 // initializer-if-any};
5281 bool hasInit = (ND->getInit() != 0);
Fariborz Jahanian104dbf92012-04-11 23:57:12 +00005282 // FIXME. rewriter does not support __block c++ objects which
5283 // require construction.
Fariborz Jahanian65a7c682012-04-26 23:20:25 +00005284 if (hasInit)
5285 if (CXXConstructExpr *CExp = dyn_cast<CXXConstructExpr>(ND->getInit())) {
5286 CXXConstructorDecl *CXXDecl = CExp->getConstructor();
5287 if (CXXDecl && CXXDecl->isDefaultConstructor())
5288 hasInit = false;
5289 }
5290
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005291 unsigned flags = 0;
5292 if (HasCopyAndDispose)
5293 flags |= BLOCK_HAS_COPY_DISPOSE;
5294 Name = ND->getNameAsString();
5295 ByrefType.clear();
5296 RewriteByRefString(ByrefType, Name, ND);
5297 std::string ForwardingCastType("(");
5298 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian8247c4e2012-04-24 16:45:27 +00005299 ByrefType += " " + Name + " = {(void*)";
5300 ByrefType += utostr(isa);
5301 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
5302 ByrefType += utostr(flags);
5303 ByrefType += ", ";
5304 ByrefType += "sizeof(";
5305 RewriteByRefString(ByrefType, Name, ND);
5306 ByrefType += ")";
5307 if (HasCopyAndDispose) {
5308 ByrefType += ", __Block_byref_id_object_copy_";
5309 ByrefType += utostr(flag);
5310 ByrefType += ", __Block_byref_id_object_dispose_";
5311 ByrefType += utostr(flag);
5312 }
5313
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00005314 if (!firstDecl) {
5315 // In multiple __block declarations, and for all but 1st declaration,
5316 // find location of the separating comma. This would be start location
5317 // where new text is to be inserted.
5318 DeclLoc = ND->getLocation();
5319 const char *startDeclBuf = SM->getCharacterData(DeclLoc);
5320 const char *commaBuf = startDeclBuf;
5321 while (*commaBuf != ',')
5322 commaBuf--;
5323 assert((*commaBuf == ',') && "RewriteByRefVar: can't find ','");
5324 DeclLoc = DeclLoc.getLocWithOffset(commaBuf - startDeclBuf);
5325 startBuf = commaBuf;
5326 }
5327
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005328 if (!hasInit) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005329 ByrefType += "};\n";
5330 unsigned nameSize = Name.size();
5331 // for block or function pointer declaration. Name is aleady
5332 // part of the declaration.
5333 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
5334 nameSize = 1;
5335 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
5336 }
5337 else {
Fariborz Jahanian8247c4e2012-04-24 16:45:27 +00005338 ByrefType += ", ";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005339 SourceLocation startLoc;
5340 Expr *E = ND->getInit();
5341 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5342 startLoc = ECE->getLParenLoc();
5343 else
5344 startLoc = E->getLocStart();
5345 startLoc = SM->getExpansionLoc(startLoc);
5346 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005347 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005348
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00005349 const char separator = lastDecl ? ';' : ',';
5350 const char *startInitializerBuf = SM->getCharacterData(startLoc);
5351 const char *separatorBuf = strchr(startInitializerBuf, separator);
5352 assert((*separatorBuf == separator) &&
5353 "RewriteByRefVar: can't find ';' or ','");
5354 SourceLocation separatorLoc =
5355 startLoc.getLocWithOffset(separatorBuf-startInitializerBuf);
5356
5357 InsertText(separatorLoc, lastDecl ? "}" : "};\n");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005358 }
5359 return;
5360}
5361
5362void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
5363 // Add initializers for any closure decl refs.
5364 GetBlockDeclRefExprs(Exp->getBody());
5365 if (BlockDeclRefs.size()) {
5366 // Unique all "by copy" declarations.
5367 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00005368 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005369 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5370 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5371 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5372 }
5373 }
5374 // Unique all "by ref" declarations.
5375 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00005376 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005377 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5378 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5379 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5380 }
5381 }
5382 // Find any imported blocks...they will need special attention.
5383 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00005384 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005385 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5386 BlockDeclRefs[i]->getType()->isBlockPointerType())
5387 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
5388 }
5389}
5390
5391FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) {
5392 IdentifierInfo *ID = &Context->Idents.get(name);
5393 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
5394 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
5395 SourceLocation(), ID, FType, 0, SC_Extern,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00005396 false, false);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005397}
5398
5399Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp,
Craig Topper6b9240e2013-07-05 19:34:19 +00005400 const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs) {
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +00005401
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005402 const BlockDecl *block = Exp->getBlockDecl();
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +00005403
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005404 Blocks.push_back(Exp);
5405
5406 CollectBlockDeclRefInfo(Exp);
5407
5408 // Add inner imported variables now used in current block.
5409 int countOfInnerDecls = 0;
5410 if (!InnerBlockDeclRefs.empty()) {
5411 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
John McCallf4b88a42012-03-10 09:33:50 +00005412 DeclRefExpr *Exp = InnerBlockDeclRefs[i];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005413 ValueDecl *VD = Exp->getDecl();
John McCallf4b88a42012-03-10 09:33:50 +00005414 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005415 // We need to save the copied-in variables in nested
5416 // blocks because it is needed at the end for some of the API generations.
5417 // See SynthesizeBlockLiterals routine.
5418 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5419 BlockDeclRefs.push_back(Exp);
5420 BlockByCopyDeclsPtrSet.insert(VD);
5421 BlockByCopyDecls.push_back(VD);
5422 }
John McCallf4b88a42012-03-10 09:33:50 +00005423 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005424 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5425 BlockDeclRefs.push_back(Exp);
5426 BlockByRefDeclsPtrSet.insert(VD);
5427 BlockByRefDecls.push_back(VD);
5428 }
5429 }
5430 // Find any imported blocks...they will need special attention.
5431 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00005432 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005433 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5434 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5435 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
5436 }
5437 InnerDeclRefsCount.push_back(countOfInnerDecls);
5438
5439 std::string FuncName;
5440
5441 if (CurFunctionDef)
5442 FuncName = CurFunctionDef->getNameAsString();
5443 else if (CurMethodDef)
5444 BuildUniqueMethodName(FuncName, CurMethodDef);
5445 else if (GlobalVarDecl)
5446 FuncName = std::string(GlobalVarDecl->getNameAsString());
5447
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00005448 bool GlobalBlockExpr =
5449 block->getDeclContext()->getRedeclContext()->isFileContext();
5450
5451 if (GlobalBlockExpr && !GlobalVarDecl) {
5452 Diags.Report(block->getLocation(), GlobalBlockRewriteFailedDiag);
5453 GlobalBlockExpr = false;
5454 }
5455
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005456 std::string BlockNumber = utostr(Blocks.size()-1);
5457
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005458 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
5459
5460 // Get a pointer to the function type so we can cast appropriately.
5461 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5462 QualType FType = Context->getPointerType(BFT);
5463
5464 FunctionDecl *FD;
5465 Expr *NewRep;
5466
Benjamin Kramere5753592013-09-09 14:48:42 +00005467 // Simulate a constructor call...
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00005468 std::string Tag;
5469
5470 if (GlobalBlockExpr)
5471 Tag = "__global_";
5472 else
5473 Tag = "__";
5474 Tag += FuncName + "_block_impl_" + BlockNumber;
5475
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005476 FD = SynthBlockInitFunctionDecl(Tag);
John McCallf4b88a42012-03-10 09:33:50 +00005477 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005478 SourceLocation());
5479
5480 SmallVector<Expr*, 4> InitExprs;
5481
5482 // Initialize the block function.
5483 FD = SynthBlockInitFunctionDecl(Func);
John McCallf4b88a42012-03-10 09:33:50 +00005484 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5485 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005486 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5487 CK_BitCast, Arg);
5488 InitExprs.push_back(castExpr);
5489
5490 // Initialize the block descriptor.
5491 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
5492
5493 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
5494 SourceLocation(), SourceLocation(),
5495 &Context->Idents.get(DescData.c_str()),
5496 Context->VoidPtrTy, 0,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00005497 SC_Static);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005498 UnaryOperator *DescRefExpr =
John McCallf4b88a42012-03-10 09:33:50 +00005499 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005500 Context->VoidPtrTy,
5501 VK_LValue,
5502 SourceLocation()),
5503 UO_AddrOf,
5504 Context->getPointerType(Context->VoidPtrTy),
5505 VK_RValue, OK_Ordinary,
5506 SourceLocation());
5507 InitExprs.push_back(DescRefExpr);
5508
5509 // Add initializers for any closure decl refs.
5510 if (BlockDeclRefs.size()) {
5511 Expr *Exp;
5512 // Output all "by copy" declarations.
Craig Topper09d19ef2013-07-04 03:08:24 +00005513 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005514 E = BlockByCopyDecls.end(); I != E; ++I) {
5515 if (isObjCType((*I)->getType())) {
5516 // FIXME: Conform to ABI ([[obj retain] autorelease]).
5517 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005518 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5519 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005520 if (HasLocalVariableExternalStorage(*I)) {
5521 QualType QT = (*I)->getType();
5522 QT = Context->getPointerType(QT);
5523 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5524 OK_Ordinary, SourceLocation());
5525 }
5526 } else if (isTopLevelBlockPointerType((*I)->getType())) {
5527 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005528 Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5529 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005530 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5531 CK_BitCast, Arg);
5532 } else {
5533 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005534 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5535 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005536 if (HasLocalVariableExternalStorage(*I)) {
5537 QualType QT = (*I)->getType();
5538 QT = Context->getPointerType(QT);
5539 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5540 OK_Ordinary, SourceLocation());
5541 }
5542
5543 }
5544 InitExprs.push_back(Exp);
5545 }
5546 // Output all "by ref" declarations.
Craig Topper09d19ef2013-07-04 03:08:24 +00005547 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005548 E = BlockByRefDecls.end(); I != E; ++I) {
5549 ValueDecl *ND = (*I);
5550 std::string Name(ND->getNameAsString());
5551 std::string RecName;
5552 RewriteByRefString(RecName, Name, ND, true);
5553 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5554 + sizeof("struct"));
5555 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5556 SourceLocation(), SourceLocation(),
5557 II);
5558 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5559 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5560
5561 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005562 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005563 SourceLocation());
5564 bool isNestedCapturedVar = false;
5565 if (block)
5566 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
5567 ce = block->capture_end(); ci != ce; ++ci) {
5568 const VarDecl *variable = ci->getVariable();
5569 if (variable == ND && ci->isNested()) {
5570 assert (ci->isByRef() &&
5571 "SynthBlockInitExpr - captured block variable is not byref");
5572 isNestedCapturedVar = true;
5573 break;
5574 }
5575 }
5576 // captured nested byref variable has its address passed. Do not take
5577 // its address again.
5578 if (!isNestedCapturedVar)
5579 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
5580 Context->getPointerType(Exp->getType()),
5581 VK_RValue, OK_Ordinary, SourceLocation());
5582 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
5583 InitExprs.push_back(Exp);
5584 }
5585 }
5586 if (ImportedBlockDecls.size()) {
5587 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5588 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
5589 unsigned IntSize =
5590 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5591 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5592 Context->IntTy, SourceLocation());
5593 InitExprs.push_back(FlagExp);
5594 }
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00005595 NewRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005596 FType, VK_LValue, SourceLocation());
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00005597
5598 if (GlobalBlockExpr) {
5599 assert (GlobalConstructionExp == 0 &&
5600 "SynthBlockInitExpr - GlobalConstructionExp must be null");
5601 GlobalConstructionExp = NewRep;
5602 NewRep = DRE;
5603 }
5604
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005605 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
5606 Context->getPointerType(NewRep->getType()),
5607 VK_RValue, OK_Ordinary, SourceLocation());
5608 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
5609 NewRep);
5610 BlockDeclRefs.clear();
5611 BlockByRefDecls.clear();
5612 BlockByRefDeclsPtrSet.clear();
5613 BlockByCopyDecls.clear();
5614 BlockByCopyDeclsPtrSet.clear();
5615 ImportedBlockDecls.clear();
5616 return NewRep;
5617}
5618
5619bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
5620 if (const ObjCForCollectionStmt * CS =
5621 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
5622 return CS->getElement() == DS;
5623 return false;
5624}
5625
5626//===----------------------------------------------------------------------===//
5627// Function Body / Expression rewriting
5628//===----------------------------------------------------------------------===//
5629
5630Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
5631 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5632 isa<DoStmt>(S) || isa<ForStmt>(S))
5633 Stmts.push_back(S);
5634 else if (isa<ObjCForCollectionStmt>(S)) {
5635 Stmts.push_back(S);
5636 ObjCBcLabelNo.push_back(++BcLabelCount);
5637 }
5638
5639 // Pseudo-object operations and ivar references need special
5640 // treatment because we're going to recursively rewrite them.
5641 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
5642 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
5643 return RewritePropertyOrImplicitSetter(PseudoOp);
5644 } else {
5645 return RewritePropertyOrImplicitGetter(PseudoOp);
5646 }
5647 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5648 return RewriteObjCIvarRefExpr(IvarRefExpr);
5649 }
Fariborz Jahanian9ffd1ae2013-02-08 18:57:50 +00005650 else if (isa<OpaqueValueExpr>(S))
5651 S = cast<OpaqueValueExpr>(S)->getSourceExpr();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005652
5653 SourceRange OrigStmtRange = S->getSourceRange();
5654
5655 // Perform a bottom up rewrite of all children.
5656 for (Stmt::child_range CI = S->children(); CI; ++CI)
5657 if (*CI) {
5658 Stmt *childStmt = (*CI);
5659 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
5660 if (newStmt) {
5661 *CI = newStmt;
5662 }
5663 }
5664
5665 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
John McCallf4b88a42012-03-10 09:33:50 +00005666 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005667 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5668 InnerContexts.insert(BE->getBlockDecl());
5669 ImportedLocalExternalDecls.clear();
5670 GetInnerBlockDeclRefExprs(BE->getBody(),
5671 InnerBlockDeclRefs, InnerContexts);
5672 // Rewrite the block body in place.
5673 Stmt *SaveCurrentBody = CurrentBody;
5674 CurrentBody = BE->getBody();
5675 PropParentMap = 0;
5676 // block literal on rhs of a property-dot-sytax assignment
5677 // must be replaced by its synthesize ast so getRewrittenText
5678 // works as expected. In this case, what actually ends up on RHS
5679 // is the blockTranscribed which is the helper function for the
5680 // block literal; as in: self.c = ^() {[ace ARR];};
5681 bool saveDisableReplaceStmt = DisableReplaceStmt;
5682 DisableReplaceStmt = false;
5683 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
5684 DisableReplaceStmt = saveDisableReplaceStmt;
5685 CurrentBody = SaveCurrentBody;
5686 PropParentMap = 0;
5687 ImportedLocalExternalDecls.clear();
5688 // Now we snarf the rewritten text and stash it away for later use.
5689 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
5690 RewrittenBlockExprs[BE] = Str;
5691
5692 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5693
5694 //blockTranscribed->dump();
5695 ReplaceStmt(S, blockTranscribed);
5696 return blockTranscribed;
5697 }
5698 // Handle specific things.
5699 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5700 return RewriteAtEncode(AtEncode);
5701
5702 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5703 return RewriteAtSelector(AtSelector);
5704
5705 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5706 return RewriteObjCStringLiteral(AtString);
Fariborz Jahanian55947042012-03-27 20:17:30 +00005707
5708 if (ObjCBoolLiteralExpr *BoolLitExpr = dyn_cast<ObjCBoolLiteralExpr>(S))
5709 return RewriteObjCBoolLiteralExpr(BoolLitExpr);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00005710
Patrick Beardeb382ec2012-04-19 00:25:12 +00005711 if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(S))
5712 return RewriteObjCBoxedExpr(BoxedExpr);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00005713
5714 if (ObjCArrayLiteral *ArrayLitExpr = dyn_cast<ObjCArrayLiteral>(S))
5715 return RewriteObjCArrayLiteralExpr(ArrayLitExpr);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00005716
5717 if (ObjCDictionaryLiteral *DictionaryLitExpr =
5718 dyn_cast<ObjCDictionaryLiteral>(S))
5719 return RewriteObjCDictionaryLiteralExpr(DictionaryLitExpr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005720
5721 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
5722#if 0
5723 // Before we rewrite it, put the original message expression in a comment.
5724 SourceLocation startLoc = MessExpr->getLocStart();
5725 SourceLocation endLoc = MessExpr->getLocEnd();
5726
5727 const char *startBuf = SM->getCharacterData(startLoc);
5728 const char *endBuf = SM->getCharacterData(endLoc);
5729
5730 std::string messString;
5731 messString += "// ";
5732 messString.append(startBuf, endBuf-startBuf+1);
5733 messString += "\n";
5734
5735 // FIXME: Missing definition of
5736 // InsertText(clang::SourceLocation, char const*, unsigned int).
5737 // InsertText(startLoc, messString.c_str(), messString.size());
5738 // Tried this, but it didn't work either...
5739 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
5740#endif
5741 return RewriteMessageExpr(MessExpr);
5742 }
5743
Fariborz Jahanian042b91d2012-05-23 23:47:20 +00005744 if (ObjCAutoreleasePoolStmt *StmtAutoRelease =
5745 dyn_cast<ObjCAutoreleasePoolStmt>(S)) {
5746 return RewriteObjCAutoreleasePoolStmt(StmtAutoRelease);
5747 }
5748
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005749 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5750 return RewriteObjCTryStmt(StmtTry);
5751
5752 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5753 return RewriteObjCSynchronizedStmt(StmtTry);
5754
5755 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5756 return RewriteObjCThrowStmt(StmtThrow);
5757
5758 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5759 return RewriteObjCProtocolExpr(ProtocolExp);
5760
5761 if (ObjCForCollectionStmt *StmtForCollection =
5762 dyn_cast<ObjCForCollectionStmt>(S))
5763 return RewriteObjCForCollectionStmt(StmtForCollection,
5764 OrigStmtRange.getEnd());
5765 if (BreakStmt *StmtBreakStmt =
5766 dyn_cast<BreakStmt>(S))
5767 return RewriteBreakStmt(StmtBreakStmt);
5768 if (ContinueStmt *StmtContinueStmt =
5769 dyn_cast<ContinueStmt>(S))
5770 return RewriteContinueStmt(StmtContinueStmt);
5771
5772 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
5773 // and cast exprs.
5774 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5775 // FIXME: What we're doing here is modifying the type-specifier that
5776 // precedes the first Decl. In the future the DeclGroup should have
5777 // a separate type-specifier that we can rewrite.
5778 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5779 // the context of an ObjCForCollectionStmt. For example:
5780 // NSArray *someArray;
5781 // for (id <FooProtocol> index in someArray) ;
5782 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5783 // and it depends on the original text locations/positions.
5784 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
5785 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
5786
5787 // Blocks rewrite rules.
5788 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5789 DI != DE; ++DI) {
5790 Decl *SD = *DI;
5791 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
5792 if (isTopLevelBlockPointerType(ND->getType()))
5793 RewriteBlockPointerDecl(ND);
5794 else if (ND->getType()->isFunctionPointerType())
5795 CheckFunctionPointerDecl(ND->getType(), ND);
5796 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
5797 if (VD->hasAttr<BlocksAttr>()) {
5798 static unsigned uniqueByrefDeclCount = 0;
5799 assert(!BlockByRefDeclNo.count(ND) &&
5800 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5801 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00005802 RewriteByRefVar(VD, (DI == DS->decl_begin()), ((DI+1) == DE));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005803 }
5804 else
5805 RewriteTypeOfDecl(VD);
5806 }
5807 }
5808 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
5809 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5810 RewriteBlockPointerDecl(TD);
5811 else if (TD->getUnderlyingType()->isFunctionPointerType())
5812 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5813 }
5814 }
5815 }
5816
5817 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5818 RewriteObjCQualifiedInterfaceTypes(CE);
5819
5820 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5821 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5822 assert(!Stmts.empty() && "Statement stack is empty");
5823 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5824 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
5825 && "Statement stack mismatch");
5826 Stmts.pop_back();
5827 }
5828 // Handle blocks rewriting.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005829 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5830 ValueDecl *VD = DRE->getDecl();
5831 if (VD->hasAttr<BlocksAttr>())
5832 return RewriteBlockDeclRefExpr(DRE);
5833 if (HasLocalVariableExternalStorage(VD))
5834 return RewriteLocalVariableExternalStorage(DRE);
5835 }
5836
5837 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
5838 if (CE->getCallee()->getType()->isBlockPointerType()) {
5839 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
5840 ReplaceStmt(S, BlockCall);
5841 return BlockCall;
5842 }
5843 }
5844 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
5845 RewriteCastExpr(CE);
5846 }
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00005847 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5848 RewriteImplicitCastObjCExpr(ICE);
5849 }
Fariborz Jahanian43aa1c32012-04-16 22:14:01 +00005850#if 0
Fariborz Jahanian653b7cf2012-04-13 18:00:54 +00005851
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005852 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5853 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5854 ICE->getSubExpr(),
5855 SourceLocation());
5856 // Get the new text.
5857 std::string SStr;
5858 llvm::raw_string_ostream Buf(SStr);
Richard Smithd1420c62012-08-16 03:56:14 +00005859 Replacement->printPretty(Buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005860 const std::string &Str = Buf.str();
5861
5862 printf("CAST = %s\n", &Str[0]);
5863 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5864 delete S;
5865 return Replacement;
5866 }
5867#endif
5868 // Return this stmt unmodified.
5869 return S;
5870}
5871
5872void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
5873 for (RecordDecl::field_iterator i = RD->field_begin(),
5874 e = RD->field_end(); i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00005875 FieldDecl *FD = *i;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005876 if (isTopLevelBlockPointerType(FD->getType()))
5877 RewriteBlockPointerDecl(FD);
5878 if (FD->getType()->isObjCQualifiedIdType() ||
5879 FD->getType()->isObjCQualifiedInterfaceType())
5880 RewriteObjCQualifiedInterfaceTypes(FD);
5881 }
5882}
5883
5884/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5885/// main file of the input.
5886void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
5887 switch (D->getKind()) {
5888 case Decl::Function: {
5889 FunctionDecl *FD = cast<FunctionDecl>(D);
5890 if (FD->isOverloadedOperator())
5891 return;
5892
5893 // Since function prototypes don't have ParmDecl's, we check the function
5894 // prototype. This enables us to rewrite function declarations and
5895 // definitions using the same code.
5896 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
5897
Argyrios Kyrtzidis9335df32012-02-12 04:48:45 +00005898 if (!FD->isThisDeclarationADefinition())
5899 break;
5900
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005901 // FIXME: If this should support Obj-C++, support CXXTryStmt
5902 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
5903 CurFunctionDef = FD;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005904 CurrentBody = Body;
5905 Body =
5906 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5907 FD->setBody(Body);
5908 CurrentBody = 0;
5909 if (PropParentMap) {
5910 delete PropParentMap;
5911 PropParentMap = 0;
5912 }
5913 // This synthesizes and inserts the block "impl" struct, invoke function,
5914 // and any copy/dispose helper functions.
5915 InsertBlockLiteralsWithinFunction(FD);
Fariborz Jahanian96205962012-11-06 17:30:23 +00005916 RewriteLineDirective(D);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005917 CurFunctionDef = 0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005918 }
5919 break;
5920 }
5921 case Decl::ObjCMethod: {
5922 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
5923 if (CompoundStmt *Body = MD->getCompoundBody()) {
5924 CurMethodDef = MD;
5925 CurrentBody = Body;
5926 Body =
5927 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5928 MD->setBody(Body);
5929 CurrentBody = 0;
5930 if (PropParentMap) {
5931 delete PropParentMap;
5932 PropParentMap = 0;
5933 }
5934 InsertBlockLiteralsWithinMethod(MD);
Fariborz Jahanian96205962012-11-06 17:30:23 +00005935 RewriteLineDirective(D);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005936 CurMethodDef = 0;
5937 }
5938 break;
5939 }
5940 case Decl::ObjCImplementation: {
5941 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
5942 ClassImplementation.push_back(CI);
5943 break;
5944 }
5945 case Decl::ObjCCategoryImpl: {
5946 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
5947 CategoryImplementation.push_back(CI);
5948 break;
5949 }
5950 case Decl::Var: {
5951 VarDecl *VD = cast<VarDecl>(D);
5952 RewriteObjCQualifiedInterfaceTypes(VD);
5953 if (isTopLevelBlockPointerType(VD->getType()))
5954 RewriteBlockPointerDecl(VD);
5955 else if (VD->getType()->isFunctionPointerType()) {
5956 CheckFunctionPointerDecl(VD->getType(), VD);
5957 if (VD->getInit()) {
5958 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5959 RewriteCastExpr(CE);
5960 }
5961 }
5962 } else if (VD->getType()->isRecordType()) {
5963 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5964 if (RD->isCompleteDefinition())
5965 RewriteRecordBody(RD);
5966 }
5967 if (VD->getInit()) {
5968 GlobalVarDecl = VD;
5969 CurrentBody = VD->getInit();
5970 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
5971 CurrentBody = 0;
5972 if (PropParentMap) {
5973 delete PropParentMap;
5974 PropParentMap = 0;
5975 }
5976 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
5977 GlobalVarDecl = 0;
5978
5979 // This is needed for blocks.
5980 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5981 RewriteCastExpr(CE);
5982 }
5983 }
5984 break;
5985 }
5986 case Decl::TypeAlias:
5987 case Decl::Typedef: {
5988 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
5989 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5990 RewriteBlockPointerDecl(TD);
5991 else if (TD->getUnderlyingType()->isFunctionPointerType())
5992 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
Fariborz Jahanianf9f30792013-04-03 19:11:21 +00005993 else
5994 RewriteObjCQualifiedInterfaceTypes(TD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005995 }
5996 break;
5997 }
5998 case Decl::CXXRecord:
5999 case Decl::Record: {
6000 RecordDecl *RD = cast<RecordDecl>(D);
6001 if (RD->isCompleteDefinition())
6002 RewriteRecordBody(RD);
6003 break;
6004 }
6005 default:
6006 break;
6007 }
6008 // Nothing yet.
6009}
6010
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006011/// Write_ProtocolExprReferencedMetadata - This routine writer out the
6012/// protocol reference symbols in the for of:
6013/// struct _protocol_t *PROTOCOL_REF = &PROTOCOL_METADATA.
6014static void Write_ProtocolExprReferencedMetadata(ASTContext *Context,
6015 ObjCProtocolDecl *PDecl,
6016 std::string &Result) {
6017 // Also output .objc_protorefs$B section and its meta-data.
6018 if (Context->getLangOpts().MicrosoftExt)
Fariborz Jahanianbd78cfa2012-04-27 21:39:49 +00006019 Result += "static ";
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006020 Result += "struct _protocol_t *";
6021 Result += "_OBJC_PROTOCOL_REFERENCE_$_";
6022 Result += PDecl->getNameAsString();
6023 Result += " = &";
6024 Result += "_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
6025 Result += ";\n";
6026}
6027
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006028void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
6029 if (Diags.hasErrorOccurred())
6030 return;
6031
6032 RewriteInclude();
6033
Fariborz Jahanian31c4a4b2013-02-07 22:50:40 +00006034 for (unsigned i = 0, e = FunctionDefinitionsSeen.size(); i < e; i++) {
6035 // translation of function bodies were postponed untill all class and
6036 // their extensions and implementations are seen. This is because, we
6037 // cannot build grouping structs for bitfields untill they are all seen.
6038 FunctionDecl *FDecl = FunctionDefinitionsSeen[i];
6039 HandleTopLevelSingleDecl(FDecl);
6040 }
6041
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006042 // Here's a great place to add any extra declarations that may be needed.
6043 // Write out meta data for each @protocol(<expr>).
6044 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006045 E = ProtocolExprDecls.end(); I != E; ++I) {
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006046 RewriteObjCProtocolMetaData(*I, Preamble);
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006047 Write_ProtocolExprReferencedMetadata(Context, (*I), Preamble);
6048 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006049
6050 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +00006051
6052 if (ClassImplementation.size() || CategoryImplementation.size())
6053 RewriteImplementations();
6054
Fariborz Jahanian57317782012-02-21 23:58:41 +00006055 for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) {
6056 ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i];
6057 // Write struct declaration for the class matching its ivar declarations.
6058 // Note that for modern abi, this is postponed until the end of TU
6059 // because class extensions and the implementation might declare their own
6060 // private ivars.
6061 RewriteInterfaceDecl(CDecl);
6062 }
Fariborz Jahanian31c4a4b2013-02-07 22:50:40 +00006063
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006064 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
6065 // we are done.
6066 if (const RewriteBuffer *RewriteBuf =
6067 Rewrite.getRewriteBufferFor(MainFileID)) {
6068 //printf("Changed:\n");
6069 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
6070 } else {
6071 llvm::errs() << "No changes\n";
6072 }
6073
6074 if (ClassImplementation.size() || CategoryImplementation.size() ||
6075 ProtocolExprDecls.size()) {
6076 // Rewrite Objective-c meta data*
6077 std::string ResultStr;
6078 RewriteMetaDataIntoBuffer(ResultStr);
6079 // Emit metadata.
6080 *OutFile << ResultStr;
6081 }
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006082 // Emit ImageInfo;
6083 {
6084 std::string ResultStr;
6085 WriteImageInfo(ResultStr);
6086 *OutFile << ResultStr;
6087 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006088 OutFile->flush();
6089}
6090
6091void RewriteModernObjC::Initialize(ASTContext &context) {
6092 InitializeCommon(context);
6093
Fariborz Jahanian6991bc52012-03-10 17:45:38 +00006094 Preamble += "#ifndef __OBJC2__\n";
6095 Preamble += "#define __OBJC2__\n";
6096 Preamble += "#endif\n";
6097
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006098 // declaring objc_selector outside the parameter list removes a silly
6099 // scope related warning...
6100 if (IsHeader)
6101 Preamble = "#pragma once\n";
6102 Preamble += "struct objc_selector; struct objc_class;\n";
Fariborz Jahaniane2d87bc2012-04-12 23:52:52 +00006103 Preamble += "struct __rw_objc_super { \n\tstruct objc_object *object; ";
6104 Preamble += "\n\tstruct objc_object *superClass; ";
6105 // Add a constructor for creating temporary objects.
6106 Preamble += "\n\t__rw_objc_super(struct objc_object *o, struct objc_object *s) ";
6107 Preamble += ": object(o), superClass(s) {} ";
6108 Preamble += "\n};\n";
6109
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006110 if (LangOpts.MicrosoftExt) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006111 // Define all sections using syntax that makes sense.
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006112 // These are currently generated.
6113 Preamble += "\n#pragma section(\".objc_classlist$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006114 Preamble += "#pragma section(\".objc_catlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006115 Preamble += "#pragma section(\".objc_imageinfo$B\", long, read, write)\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006116 Preamble += "#pragma section(\".objc_nlclslist$B\", long, read, write)\n";
6117 Preamble += "#pragma section(\".objc_nlcatlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006118 // These are generated but not necessary for functionality.
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006119 Preamble += "#pragma section(\".cat_cls_meth$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006120 Preamble += "#pragma section(\".inst_meth$B\", long, read, write)\n";
6121 Preamble += "#pragma section(\".cls_meth$B\", long, read, write)\n";
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00006122 Preamble += "#pragma section(\".objc_ivar$B\", long, read, write)\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006123
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006124 // These need be generated for performance. Currently they are not,
6125 // using API calls instead.
6126 Preamble += "#pragma section(\".objc_selrefs$B\", long, read, write)\n";
6127 Preamble += "#pragma section(\".objc_classrefs$B\", long, read, write)\n";
6128 Preamble += "#pragma section(\".objc_superrefs$B\", long, read, write)\n";
6129
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006130 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006131 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
6132 Preamble += "typedef struct objc_object Protocol;\n";
6133 Preamble += "#define _REWRITER_typedef_Protocol\n";
6134 Preamble += "#endif\n";
6135 if (LangOpts.MicrosoftExt) {
6136 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
6137 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
Fariborz Jahanian5cf6b6c2012-03-21 23:41:04 +00006138 }
6139 else
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006140 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Fariborz Jahanian5cf6b6c2012-03-21 23:41:04 +00006141
6142 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend(void);\n";
6143 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper(void);\n";
6144 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_stret(void);\n";
6145 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper_stret(void);\n";
6146 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_fpret(void);\n";
6147
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00006148 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getClass";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006149 Preamble += "(const char *);\n";
6150 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
6151 Preamble += "(struct objc_class *);\n";
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00006152 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getMetaClass";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006153 Preamble += "(const char *);\n";
Fariborz Jahanian55261af2012-03-19 18:11:32 +00006154 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw( struct objc_object *);\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006155 // @synchronized hooks.
Aaron Ballman2d234d732012-09-06 16:44:16 +00006156 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_enter( struct objc_object *);\n";
6157 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_exit( struct objc_object *);\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006158 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Fariborz Jahaniane38f08a2013-09-05 17:17:32 +00006159 Preamble += "#ifdef _WIN64\n";
6160 Preamble += "typedef unsigned long long _WIN_NSUInteger;\n";
6161 Preamble += "#else\n";
6162 Preamble += "typedef unsigned int _WIN_NSUInteger;\n";
6163 Preamble += "#endif\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006164 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
6165 Preamble += "struct __objcFastEnumerationState {\n\t";
6166 Preamble += "unsigned long state;\n\t";
6167 Preamble += "void **itemsPtr;\n\t";
6168 Preamble += "unsigned long *mutationsPtr;\n\t";
6169 Preamble += "unsigned long extra[5];\n};\n";
6170 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
6171 Preamble += "#define __FASTENUMERATIONSTATE\n";
6172 Preamble += "#endif\n";
6173 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
6174 Preamble += "struct __NSConstantStringImpl {\n";
6175 Preamble += " int *isa;\n";
6176 Preamble += " int flags;\n";
6177 Preamble += " char *str;\n";
6178 Preamble += " long length;\n";
6179 Preamble += "};\n";
6180 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
6181 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
6182 Preamble += "#else\n";
6183 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
6184 Preamble += "#endif\n";
6185 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
6186 Preamble += "#endif\n";
6187 // Blocks preamble.
6188 Preamble += "#ifndef BLOCK_IMPL\n";
6189 Preamble += "#define BLOCK_IMPL\n";
6190 Preamble += "struct __block_impl {\n";
6191 Preamble += " void *isa;\n";
6192 Preamble += " int Flags;\n";
6193 Preamble += " int Reserved;\n";
6194 Preamble += " void *FuncPtr;\n";
6195 Preamble += "};\n";
6196 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
6197 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
6198 Preamble += "extern \"C\" __declspec(dllexport) "
6199 "void _Block_object_assign(void *, const void *, const int);\n";
6200 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
6201 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
6202 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
6203 Preamble += "#else\n";
6204 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
6205 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
6206 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
6207 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
6208 Preamble += "#endif\n";
6209 Preamble += "#endif\n";
6210 if (LangOpts.MicrosoftExt) {
6211 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
6212 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
6213 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
6214 Preamble += "#define __attribute__(X)\n";
6215 Preamble += "#endif\n";
Fariborz Jahanian5ce28272012-04-12 16:33:31 +00006216 Preamble += "#ifndef __weak\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006217 Preamble += "#define __weak\n";
Fariborz Jahanian5ce28272012-04-12 16:33:31 +00006218 Preamble += "#endif\n";
6219 Preamble += "#ifndef __block\n";
6220 Preamble += "#define __block\n";
6221 Preamble += "#endif\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006222 }
6223 else {
6224 Preamble += "#define __block\n";
6225 Preamble += "#define __weak\n";
6226 }
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00006227
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00006228 // Declarations required for modern objective-c array and dictionary literals.
6229 Preamble += "\n#include <stdarg.h>\n";
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00006230 Preamble += "struct __NSContainer_literal {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00006231 Preamble += " void * *arr;\n";
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00006232 Preamble += " __NSContainer_literal (unsigned int count, ...) {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00006233 Preamble += "\tva_list marker;\n";
6234 Preamble += "\tva_start(marker, count);\n";
6235 Preamble += "\tarr = new void *[count];\n";
6236 Preamble += "\tfor (unsigned i = 0; i < count; i++)\n";
6237 Preamble += "\t arr[i] = va_arg(marker, void *);\n";
6238 Preamble += "\tva_end( marker );\n";
6239 Preamble += " };\n";
Fariborz Jahanian13a9c022012-05-02 23:53:46 +00006240 Preamble += " ~__NSContainer_literal() {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00006241 Preamble += "\tdelete[] arr;\n";
6242 Preamble += " }\n";
6243 Preamble += "};\n";
6244
Fariborz Jahanian042b91d2012-05-23 23:47:20 +00006245 // Declaration required for implementation of @autoreleasepool statement.
6246 Preamble += "extern \"C\" __declspec(dllimport) void * objc_autoreleasePoolPush(void);\n";
6247 Preamble += "extern \"C\" __declspec(dllimport) void objc_autoreleasePoolPop(void *);\n\n";
6248 Preamble += "struct __AtAutoreleasePool {\n";
6249 Preamble += " __AtAutoreleasePool() {atautoreleasepoolobj = objc_autoreleasePoolPush();}\n";
6250 Preamble += " ~__AtAutoreleasePool() {objc_autoreleasePoolPop(atautoreleasepoolobj);}\n";
6251 Preamble += " void * atautoreleasepoolobj;\n";
6252 Preamble += "};\n";
6253
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006254 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
6255 // as this avoids warning in any 64bit/32bit compilation model.
6256 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
6257}
6258
6259/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
6260/// ivar offset.
6261void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
6262 std::string &Result) {
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00006263 Result += "__OFFSETOFIVAR__(struct ";
6264 Result += ivar->getContainingInterface()->getNameAsString();
6265 if (LangOpts.MicrosoftExt)
6266 Result += "_IMPL";
6267 Result += ", ";
6268 if (ivar->isBitField())
6269 ObjCIvarBitfieldGroupDecl(ivar, Result);
6270 else
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006271 Result += ivar->getNameAsString();
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00006272 Result += ")";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006273}
6274
6275/// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
6276/// struct _prop_t {
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006277/// const char *name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006278/// char *attributes;
6279/// }
6280
6281/// struct _prop_list_t {
6282/// uint32_t entsize; // sizeof(struct _prop_t)
6283/// uint32_t count_of_properties;
6284/// struct _prop_t prop_list[count_of_properties];
6285/// }
6286
6287/// struct _protocol_t;
6288
6289/// struct _protocol_list_t {
6290/// long protocol_count; // Note, this is 32/64 bit
6291/// struct _protocol_t * protocol_list[protocol_count];
6292/// }
6293
6294/// struct _objc_method {
6295/// SEL _cmd;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006296/// const char *method_type;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006297/// char *_imp;
6298/// }
6299
6300/// struct _method_list_t {
6301/// uint32_t entsize; // sizeof(struct _objc_method)
6302/// uint32_t method_count;
6303/// struct _objc_method method_list[method_count];
6304/// }
6305
6306/// struct _protocol_t {
6307/// id isa; // NULL
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006308/// const char *protocol_name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006309/// const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006310/// const struct method_list_t *instance_methods;
6311/// const struct method_list_t *class_methods;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006312/// const struct method_list_t *optionalInstanceMethods;
6313/// const struct method_list_t *optionalClassMethods;
6314/// const struct _prop_list_t * properties;
6315/// const uint32_t size; // sizeof(struct _protocol_t)
6316/// const uint32_t flags; // = 0
6317/// const char ** extendedMethodTypes;
6318/// }
6319
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006320/// struct _ivar_t {
6321/// unsigned long int *offset; // pointer to ivar offset location
Fariborz Jahanianae932952012-02-10 20:47:10 +00006322/// const char *name;
6323/// const char *type;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006324/// uint32_t alignment;
6325/// uint32_t size;
6326/// }
6327
6328/// struct _ivar_list_t {
6329/// uint32 entsize; // sizeof(struct _ivar_t)
6330/// uint32 count;
Fariborz Jahanianae932952012-02-10 20:47:10 +00006331/// struct _ivar_t list[count];
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006332/// }
6333
6334/// struct _class_ro_t {
Fariborz Jahanian249cd102012-03-24 16:53:16 +00006335/// uint32_t flags;
6336/// uint32_t instanceStart;
6337/// uint32_t instanceSize;
6338/// uint32_t reserved; // only when building for 64bit targets
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006339/// const uint8_t *ivarLayout;
6340/// const char *name;
6341/// const struct _method_list_t *baseMethods;
6342/// const struct _protocol_list_t *baseProtocols;
6343/// const struct _ivar_list_t *ivars;
6344/// const uint8_t *weakIvarLayout;
6345/// const struct _prop_list_t *properties;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006346/// }
6347
6348/// struct _class_t {
6349/// struct _class_t *isa;
Fariborz Jahanianfd4ce2c2012-03-20 17:34:50 +00006350/// struct _class_t *superclass;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006351/// void *cache;
6352/// IMP *vtable;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006353/// struct _class_ro_t *ro;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006354/// }
6355
6356/// struct _category_t {
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006357/// const char *name;
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006358/// struct _class_t *cls;
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006359/// const struct _method_list_t *instance_methods;
6360/// const struct _method_list_t *class_methods;
6361/// const struct _protocol_list_t *protocols;
6362/// const struct _prop_list_t *properties;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006363/// }
6364
6365/// MessageRefTy - LLVM for:
6366/// struct _message_ref_t {
6367/// IMP messenger;
6368/// SEL name;
6369/// };
6370
6371/// SuperMessageRefTy - LLVM for:
6372/// struct _super_message_ref_t {
6373/// SUPER_IMP messenger;
6374/// SEL name;
6375/// };
6376
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006377static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006378 static bool meta_data_declared = false;
6379 if (meta_data_declared)
6380 return;
6381
6382 Result += "\nstruct _prop_t {\n";
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006383 Result += "\tconst char *name;\n";
6384 Result += "\tconst char *attributes;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006385 Result += "};\n";
6386
6387 Result += "\nstruct _protocol_t;\n";
6388
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006389 Result += "\nstruct _objc_method {\n";
6390 Result += "\tstruct objc_selector * _cmd;\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006391 Result += "\tconst char *method_type;\n";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006392 Result += "\tvoid *_imp;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006393 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006394
6395 Result += "\nstruct _protocol_t {\n";
6396 Result += "\tvoid * isa; // NULL\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006397 Result += "\tconst char *protocol_name;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006398 Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006399 Result += "\tconst struct method_list_t *instance_methods;\n";
6400 Result += "\tconst struct method_list_t *class_methods;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006401 Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
6402 Result += "\tconst struct method_list_t *optionalClassMethods;\n";
6403 Result += "\tconst struct _prop_list_t * properties;\n";
6404 Result += "\tconst unsigned int size; // sizeof(struct _protocol_t)\n";
6405 Result += "\tconst unsigned int flags; // = 0\n";
6406 Result += "\tconst char ** extendedMethodTypes;\n";
6407 Result += "};\n";
6408
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006409 Result += "\nstruct _ivar_t {\n";
6410 Result += "\tunsigned long int *offset; // pointer to ivar offset location\n";
Fariborz Jahanianae932952012-02-10 20:47:10 +00006411 Result += "\tconst char *name;\n";
6412 Result += "\tconst char *type;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006413 Result += "\tunsigned int alignment;\n";
6414 Result += "\tunsigned int size;\n";
6415 Result += "};\n";
6416
6417 Result += "\nstruct _class_ro_t {\n";
Fariborz Jahanian249cd102012-03-24 16:53:16 +00006418 Result += "\tunsigned int flags;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006419 Result += "\tunsigned int instanceStart;\n";
Fariborz Jahanian249cd102012-03-24 16:53:16 +00006420 Result += "\tunsigned int instanceSize;\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006421 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6422 if (Triple.getArch() == llvm::Triple::x86_64)
Fariborz Jahanian249cd102012-03-24 16:53:16 +00006423 Result += "\tunsigned int reserved;\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006424 Result += "\tconst unsigned char *ivarLayout;\n";
6425 Result += "\tconst char *name;\n";
6426 Result += "\tconst struct _method_list_t *baseMethods;\n";
6427 Result += "\tconst struct _objc_protocol_list *baseProtocols;\n";
6428 Result += "\tconst struct _ivar_list_t *ivars;\n";
6429 Result += "\tconst unsigned char *weakIvarLayout;\n";
6430 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006431 Result += "};\n";
6432
6433 Result += "\nstruct _class_t {\n";
6434 Result += "\tstruct _class_t *isa;\n";
Fariborz Jahanianfd4ce2c2012-03-20 17:34:50 +00006435 Result += "\tstruct _class_t *superclass;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006436 Result += "\tvoid *cache;\n";
6437 Result += "\tvoid *vtable;\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006438 Result += "\tstruct _class_ro_t *ro;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006439 Result += "};\n";
6440
6441 Result += "\nstruct _category_t {\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006442 Result += "\tconst char *name;\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006443 Result += "\tstruct _class_t *cls;\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006444 Result += "\tconst struct _method_list_t *instance_methods;\n";
6445 Result += "\tconst struct _method_list_t *class_methods;\n";
6446 Result += "\tconst struct _protocol_list_t *protocols;\n";
6447 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006448 Result += "};\n";
6449
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006450 Result += "extern \"C\" __declspec(dllimport) struct objc_cache _objc_empty_cache;\n";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006451 Result += "#pragma warning(disable:4273)\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006452 meta_data_declared = true;
6453}
6454
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006455static void Write_protocol_list_t_TypeDecl(std::string &Result,
6456 long super_protocol_count) {
6457 Result += "struct /*_protocol_list_t*/"; Result += " {\n";
6458 Result += "\tlong protocol_count; // Note, this is 32/64 bit\n";
6459 Result += "\tstruct _protocol_t *super_protocols[";
6460 Result += utostr(super_protocol_count); Result += "];\n";
6461 Result += "}";
6462}
6463
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006464static void Write_method_list_t_TypeDecl(std::string &Result,
6465 unsigned int method_count) {
6466 Result += "struct /*_method_list_t*/"; Result += " {\n";
6467 Result += "\tunsigned int entsize; // sizeof(struct _objc_method)\n";
6468 Result += "\tunsigned int method_count;\n";
6469 Result += "\tstruct _objc_method method_list[";
6470 Result += utostr(method_count); Result += "];\n";
6471 Result += "}";
6472}
6473
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006474static void Write__prop_list_t_TypeDecl(std::string &Result,
6475 unsigned int property_count) {
6476 Result += "struct /*_prop_list_t*/"; Result += " {\n";
6477 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6478 Result += "\tunsigned int count_of_properties;\n";
6479 Result += "\tstruct _prop_t prop_list[";
6480 Result += utostr(property_count); Result += "];\n";
6481 Result += "}";
6482}
6483
Fariborz Jahanianae932952012-02-10 20:47:10 +00006484static void Write__ivar_list_t_TypeDecl(std::string &Result,
6485 unsigned int ivar_count) {
6486 Result += "struct /*_ivar_list_t*/"; Result += " {\n";
6487 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6488 Result += "\tunsigned int count;\n";
6489 Result += "\tstruct _ivar_t ivar_list[";
6490 Result += utostr(ivar_count); Result += "];\n";
6491 Result += "}";
6492}
6493
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006494static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result,
6495 ArrayRef<ObjCProtocolDecl *> SuperProtocols,
6496 StringRef VarName,
6497 StringRef ProtocolName) {
6498 if (SuperProtocols.size() > 0) {
6499 Result += "\nstatic ";
6500 Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size());
6501 Result += " "; Result += VarName;
6502 Result += ProtocolName;
6503 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6504 Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n";
6505 for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) {
6506 ObjCProtocolDecl *SuperPD = SuperProtocols[i];
6507 Result += "\t&"; Result += "_OBJC_PROTOCOL_";
6508 Result += SuperPD->getNameAsString();
6509 if (i == e-1)
6510 Result += "\n};\n";
6511 else
6512 Result += ",\n";
6513 }
6514 }
6515}
6516
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006517static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj,
6518 ASTContext *Context, std::string &Result,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006519 ArrayRef<ObjCMethodDecl *> Methods,
6520 StringRef VarName,
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006521 StringRef TopLevelDeclName,
6522 bool MethodImpl) {
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006523 if (Methods.size() > 0) {
6524 Result += "\nstatic ";
6525 Write_method_list_t_TypeDecl(Result, Methods.size());
6526 Result += " "; Result += VarName;
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006527 Result += TopLevelDeclName;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006528 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6529 Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
6530 Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
6531 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6532 ObjCMethodDecl *MD = Methods[i];
6533 if (i == 0)
6534 Result += "\t{{(struct objc_selector *)\"";
6535 else
6536 Result += "\t{(struct objc_selector *)\"";
6537 Result += (MD)->getSelector().getAsString(); Result += "\"";
6538 Result += ", ";
6539 std::string MethodTypeString;
6540 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString);
6541 Result += "\""; Result += MethodTypeString; Result += "\"";
6542 Result += ", ";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006543 if (!MethodImpl)
6544 Result += "0";
6545 else {
6546 Result += "(void *)";
6547 Result += RewriteObj.MethodInternalNames[MD];
6548 }
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006549 if (i == e-1)
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006550 Result += "}}\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006551 else
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006552 Result += "},\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006553 }
6554 Result += "};\n";
6555 }
6556}
6557
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006558static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006559 ASTContext *Context, std::string &Result,
6560 ArrayRef<ObjCPropertyDecl *> Properties,
6561 const Decl *Container,
6562 StringRef VarName,
6563 StringRef ProtocolName) {
6564 if (Properties.size() > 0) {
6565 Result += "\nstatic ";
6566 Write__prop_list_t_TypeDecl(Result, Properties.size());
6567 Result += " "; Result += VarName;
6568 Result += ProtocolName;
6569 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6570 Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
6571 Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
6572 for (unsigned i = 0, e = Properties.size(); i < e; i++) {
6573 ObjCPropertyDecl *PropDecl = Properties[i];
6574 if (i == 0)
6575 Result += "\t{{\"";
6576 else
6577 Result += "\t{\"";
6578 Result += PropDecl->getName(); Result += "\",";
6579 std::string PropertyTypeString, QuotePropertyTypeString;
6580 Context->getObjCEncodingForPropertyDecl(PropDecl, Container, PropertyTypeString);
6581 RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
6582 Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
6583 if (i == e-1)
6584 Result += "}}\n";
6585 else
6586 Result += "},\n";
6587 }
6588 Result += "};\n";
6589 }
6590}
6591
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006592// Metadata flags
6593enum MetaDataDlags {
6594 CLS = 0x0,
6595 CLS_META = 0x1,
6596 CLS_ROOT = 0x2,
6597 OBJC2_CLS_HIDDEN = 0x10,
6598 CLS_EXCEPTION = 0x20,
6599
6600 /// (Obsolete) ARC-specific: this class has a .release_ivars method
6601 CLS_HAS_IVAR_RELEASER = 0x40,
6602 /// class was compiled with -fobjc-arr
6603 CLS_COMPILED_BY_ARC = 0x80 // (1<<7)
6604};
6605
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006606static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result,
6607 unsigned int flags,
6608 const std::string &InstanceStart,
6609 const std::string &InstanceSize,
6610 ArrayRef<ObjCMethodDecl *>baseMethods,
6611 ArrayRef<ObjCProtocolDecl *>baseProtocols,
6612 ArrayRef<ObjCIvarDecl *>ivars,
6613 ArrayRef<ObjCPropertyDecl *>Properties,
6614 StringRef VarName,
6615 StringRef ClassName) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006616 Result += "\nstatic struct _class_ro_t ";
6617 Result += VarName; Result += ClassName;
6618 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6619 Result += "\t";
6620 Result += llvm::utostr(flags); Result += ", ";
6621 Result += InstanceStart; Result += ", ";
6622 Result += InstanceSize; Result += ", \n";
6623 Result += "\t";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006624 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6625 if (Triple.getArch() == llvm::Triple::x86_64)
6626 // uint32_t const reserved; // only when building for 64bit targets
6627 Result += "(unsigned int)0, \n\t";
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006628 // const uint8_t * const ivarLayout;
6629 Result += "0, \n\t";
6630 Result += "\""; Result += ClassName; Result += "\",\n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006631 bool metaclass = ((flags & CLS_META) != 0);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006632 if (baseMethods.size() > 0) {
6633 Result += "(const struct _method_list_t *)&";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006634 if (metaclass)
6635 Result += "_OBJC_$_CLASS_METHODS_";
6636 else
6637 Result += "_OBJC_$_INSTANCE_METHODS_";
6638 Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006639 Result += ",\n\t";
6640 }
6641 else
6642 Result += "0, \n\t";
6643
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006644 if (!metaclass && baseProtocols.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006645 Result += "(const struct _objc_protocol_list *)&";
6646 Result += "_OBJC_CLASS_PROTOCOLS_$_"; Result += ClassName;
6647 Result += ",\n\t";
6648 }
6649 else
6650 Result += "0, \n\t";
6651
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006652 if (!metaclass && ivars.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006653 Result += "(const struct _ivar_list_t *)&";
6654 Result += "_OBJC_$_INSTANCE_VARIABLES_"; Result += ClassName;
6655 Result += ",\n\t";
6656 }
6657 else
6658 Result += "0, \n\t";
6659
6660 // weakIvarLayout
6661 Result += "0, \n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006662 if (!metaclass && Properties.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006663 Result += "(const struct _prop_list_t *)&";
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00006664 Result += "_OBJC_$_PROP_LIST_"; Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006665 Result += ",\n";
6666 }
6667 else
6668 Result += "0, \n";
6669
6670 Result += "};\n";
6671}
6672
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006673static void Write_class_t(ASTContext *Context, std::string &Result,
6674 StringRef VarName,
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006675 const ObjCInterfaceDecl *CDecl, bool metaclass) {
6676 bool rootClass = (!CDecl->getSuperClass());
6677 const ObjCInterfaceDecl *RootClass = CDecl;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006678
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006679 if (!rootClass) {
6680 // Find the Root class
6681 RootClass = CDecl->getSuperClass();
6682 while (RootClass->getSuperClass()) {
6683 RootClass = RootClass->getSuperClass();
6684 }
6685 }
6686
6687 if (metaclass && rootClass) {
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006688 // Need to handle a case of use of forward declaration.
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006689 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006690 Result += "extern \"C\" ";
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006691 if (CDecl->getImplementation())
6692 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006693 else
6694 Result += "__declspec(dllimport) ";
6695
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006696 Result += "struct _class_t OBJC_CLASS_$_";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006697 Result += CDecl->getNameAsString();
6698 Result += ";\n";
6699 }
6700 // Also, for possibility of 'super' metadata class not having been defined yet.
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006701 if (!rootClass) {
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006702 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006703 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006704 Result += "extern \"C\" ";
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006705 if (SuperClass->getImplementation())
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006706 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006707 else
6708 Result += "__declspec(dllimport) ";
6709
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006710 Result += "struct _class_t ";
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006711 Result += VarName;
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006712 Result += SuperClass->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006713 Result += ";\n";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006714
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006715 if (metaclass && RootClass != SuperClass) {
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006716 Result += "extern \"C\" ";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006717 if (RootClass->getImplementation())
6718 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006719 else
6720 Result += "__declspec(dllimport) ";
6721
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006722 Result += "struct _class_t ";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006723 Result += VarName;
6724 Result += RootClass->getNameAsString();
6725 Result += ";\n";
6726 }
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006727 }
6728
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006729 Result += "\nextern \"C\" __declspec(dllexport) struct _class_t ";
6730 Result += VarName; Result += CDecl->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006731 Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n";
6732 Result += "\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006733 if (metaclass) {
6734 if (!rootClass) {
6735 Result += "0, // &"; Result += VarName;
6736 Result += RootClass->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006737 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006738 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006739 Result += CDecl->getSuperClass()->getNameAsString();
6740 Result += ",\n\t";
6741 }
6742 else {
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006743 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006744 Result += CDecl->getNameAsString();
6745 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006746 Result += "0, // &OBJC_CLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006747 Result += ",\n\t";
6748 }
6749 }
6750 else {
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006751 Result += "0, // &OBJC_METACLASS_$_";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006752 Result += CDecl->getNameAsString();
6753 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006754 if (!rootClass) {
6755 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006756 Result += CDecl->getSuperClass()->getNameAsString();
6757 Result += ",\n\t";
6758 }
6759 else
6760 Result += "0,\n\t";
6761 }
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006762 Result += "0, // (void *)&_objc_empty_cache,\n\t";
6763 Result += "0, // unused, was (void *)&_objc_empty_vtable,\n\t";
6764 if (metaclass)
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006765 Result += "&_OBJC_METACLASS_RO_$_";
6766 else
6767 Result += "&_OBJC_CLASS_RO_$_";
6768 Result += CDecl->getNameAsString();
6769 Result += ",\n};\n";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006770
6771 // Add static function to initialize some of the meta-data fields.
6772 // avoid doing it twice.
6773 if (metaclass)
6774 return;
6775
6776 const ObjCInterfaceDecl *SuperClass =
6777 rootClass ? CDecl : CDecl->getSuperClass();
6778
6779 Result += "static void OBJC_CLASS_SETUP_$_";
6780 Result += CDecl->getNameAsString();
6781 Result += "(void ) {\n";
6782 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6783 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006784 Result += RootClass->getNameAsString(); Result += ";\n";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006785
6786 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006787 Result += ".superclass = ";
6788 if (rootClass)
6789 Result += "&OBJC_CLASS_$_";
6790 else
6791 Result += "&OBJC_METACLASS_$_";
6792
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006793 Result += SuperClass->getNameAsString(); Result += ";\n";
6794
6795 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6796 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6797
6798 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6799 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
6800 Result += CDecl->getNameAsString(); Result += ";\n";
6801
6802 if (!rootClass) {
6803 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6804 Result += ".superclass = "; Result += "&OBJC_CLASS_$_";
6805 Result += SuperClass->getNameAsString(); Result += ";\n";
6806 }
6807
6808 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6809 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6810 Result += "}\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006811}
6812
Fariborz Jahanian61186122012-02-17 18:40:41 +00006813static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context,
6814 std::string &Result,
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006815 ObjCCategoryDecl *CatDecl,
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006816 ObjCInterfaceDecl *ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00006817 ArrayRef<ObjCMethodDecl *> InstanceMethods,
6818 ArrayRef<ObjCMethodDecl *> ClassMethods,
6819 ArrayRef<ObjCProtocolDecl *> RefedProtocols,
6820 ArrayRef<ObjCPropertyDecl *> ClassProperties) {
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006821 StringRef CatName = CatDecl->getName();
NAKAMURA Takumi20f89392012-03-21 03:21:46 +00006822 StringRef ClassName = ClassDecl->getName();
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00006823 // must declare an extern class object in case this class is not implemented
6824 // in this TU.
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006825 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006826 Result += "extern \"C\" ";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006827 if (ClassDecl->getImplementation())
6828 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006829 else
6830 Result += "__declspec(dllimport) ";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006831
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006832 Result += "struct _class_t ";
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00006833 Result += "OBJC_CLASS_$_"; Result += ClassName;
6834 Result += ";\n";
6835
Fariborz Jahanian61186122012-02-17 18:40:41 +00006836 Result += "\nstatic struct _category_t ";
6837 Result += "_OBJC_$_CATEGORY_";
6838 Result += ClassName; Result += "_$_"; Result += CatName;
6839 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6840 Result += "{\n";
6841 Result += "\t\""; Result += ClassName; Result += "\",\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006842 Result += "\t0, // &"; Result += "OBJC_CLASS_$_"; Result += ClassName;
Fariborz Jahanian61186122012-02-17 18:40:41 +00006843 Result += ",\n";
6844 if (InstanceMethods.size() > 0) {
6845 Result += "\t(const struct _method_list_t *)&";
6846 Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_";
6847 Result += ClassName; Result += "_$_"; Result += CatName;
6848 Result += ",\n";
6849 }
6850 else
6851 Result += "\t0,\n";
6852
6853 if (ClassMethods.size() > 0) {
6854 Result += "\t(const struct _method_list_t *)&";
6855 Result += "_OBJC_$_CATEGORY_CLASS_METHODS_";
6856 Result += ClassName; Result += "_$_"; Result += CatName;
6857 Result += ",\n";
6858 }
6859 else
6860 Result += "\t0,\n";
6861
6862 if (RefedProtocols.size() > 0) {
6863 Result += "\t(const struct _protocol_list_t *)&";
6864 Result += "_OBJC_CATEGORY_PROTOCOLS_$_";
6865 Result += ClassName; Result += "_$_"; Result += CatName;
6866 Result += ",\n";
6867 }
6868 else
6869 Result += "\t0,\n";
6870
6871 if (ClassProperties.size() > 0) {
6872 Result += "\t(const struct _prop_list_t *)&"; Result += "_OBJC_$_PROP_LIST_";
6873 Result += ClassName; Result += "_$_"; Result += CatName;
6874 Result += ",\n";
6875 }
6876 else
6877 Result += "\t0,\n";
6878
6879 Result += "};\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006880
6881 // Add static function to initialize the class pointer in the category structure.
6882 Result += "static void OBJC_CATEGORY_SETUP_$_";
6883 Result += ClassDecl->getNameAsString();
6884 Result += "_$_";
6885 Result += CatName;
6886 Result += "(void ) {\n";
6887 Result += "\t_OBJC_$_CATEGORY_";
6888 Result += ClassDecl->getNameAsString();
6889 Result += "_$_";
6890 Result += CatName;
6891 Result += ".cls = "; Result += "&OBJC_CLASS_$_"; Result += ClassName;
6892 Result += ";\n}\n";
Fariborz Jahanian61186122012-02-17 18:40:41 +00006893}
6894
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006895static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj,
6896 ASTContext *Context, std::string &Result,
6897 ArrayRef<ObjCMethodDecl *> Methods,
6898 StringRef VarName,
6899 StringRef ProtocolName) {
6900 if (Methods.size() == 0)
6901 return;
6902
6903 Result += "\nstatic const char *";
6904 Result += VarName; Result += ProtocolName;
6905 Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6906 Result += "{\n";
6907 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6908 ObjCMethodDecl *MD = Methods[i];
6909 std::string MethodTypeString, QuoteMethodTypeString;
6910 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString, true);
6911 RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString);
6912 Result += "\t\""; Result += QuoteMethodTypeString; Result += "\"";
6913 if (i == e-1)
6914 Result += "\n};\n";
6915 else {
6916 Result += ",\n";
6917 }
6918 }
6919}
6920
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00006921static void Write_IvarOffsetVar(RewriteModernObjC &RewriteObj,
6922 ASTContext *Context,
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00006923 std::string &Result,
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006924 ArrayRef<ObjCIvarDecl *> Ivars,
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006925 ObjCInterfaceDecl *CDecl) {
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006926 // FIXME. visibilty of offset symbols may have to be set; for Darwin
6927 // this is what happens:
6928 /**
6929 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
6930 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
6931 Class->getVisibility() == HiddenVisibility)
6932 Visibility shoud be: HiddenVisibility;
6933 else
6934 Visibility shoud be: DefaultVisibility;
6935 */
6936
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006937 Result += "\n";
6938 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6939 ObjCIvarDecl *IvarDecl = Ivars[i];
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00006940 if (Context->getLangOpts().MicrosoftExt)
6941 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
6942
6943 if (!Context->getLangOpts().MicrosoftExt ||
6944 IvarDecl->getAccessControl() == ObjCIvarDecl::Private ||
Fariborz Jahanian117591f2012-03-10 01:34:42 +00006945 IvarDecl->getAccessControl() == ObjCIvarDecl::Package)
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006946 Result += "extern \"C\" unsigned long int ";
Fariborz Jahaniand1c84d32012-03-10 00:53:02 +00006947 else
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006948 Result += "extern \"C\" __declspec(dllexport) unsigned long int ";
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00006949 if (Ivars[i]->isBitField())
6950 RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
6951 else
6952 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006953 Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))";
6954 Result += " = ";
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00006955 RewriteObj.RewriteIvarOffsetComputation(IvarDecl, Result);
6956 Result += ";\n";
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00006957 if (Ivars[i]->isBitField()) {
6958 // skip over rest of the ivar bitfields.
6959 SKIP_BITFIELDS(i , e, Ivars);
6960 }
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006961 }
6962}
6963
Fariborz Jahanianae932952012-02-10 20:47:10 +00006964static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj,
6965 ASTContext *Context, std::string &Result,
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00006966 ArrayRef<ObjCIvarDecl *> OriginalIvars,
Fariborz Jahanianae932952012-02-10 20:47:10 +00006967 StringRef VarName,
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006968 ObjCInterfaceDecl *CDecl) {
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00006969 if (OriginalIvars.size() > 0) {
6970 Write_IvarOffsetVar(RewriteObj, Context, Result, OriginalIvars, CDecl);
6971 SmallVector<ObjCIvarDecl *, 8> Ivars;
6972 // strip off all but the first ivar bitfield from each group of ivars.
6973 // Such ivars in the ivar list table will be replaced by their grouping struct
6974 // 'ivar'.
6975 for (unsigned i = 0, e = OriginalIvars.size(); i < e; i++) {
6976 if (OriginalIvars[i]->isBitField()) {
6977 Ivars.push_back(OriginalIvars[i]);
6978 // skip over rest of the ivar bitfields.
6979 SKIP_BITFIELDS(i , e, OriginalIvars);
6980 }
6981 else
6982 Ivars.push_back(OriginalIvars[i]);
6983 }
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006984
Fariborz Jahanianae932952012-02-10 20:47:10 +00006985 Result += "\nstatic ";
6986 Write__ivar_list_t_TypeDecl(Result, Ivars.size());
6987 Result += " "; Result += VarName;
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006988 Result += CDecl->getNameAsString();
Fariborz Jahanianae932952012-02-10 20:47:10 +00006989 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6990 Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n";
6991 Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n";
6992 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6993 ObjCIvarDecl *IvarDecl = Ivars[i];
6994 if (i == 0)
6995 Result += "\t{{";
6996 else
6997 Result += "\t {";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006998 Result += "(unsigned long int *)&";
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00006999 if (Ivars[i]->isBitField())
7000 RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
7001 else
7002 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahaniandb649232012-02-13 20:59:02 +00007003 Result += ", ";
Fariborz Jahanianae932952012-02-10 20:47:10 +00007004
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00007005 Result += "\"";
7006 if (Ivars[i]->isBitField())
7007 RewriteObj.ObjCIvarBitfieldGroupDecl(Ivars[i], Result);
7008 else
7009 Result += IvarDecl->getName();
7010 Result += "\", ";
7011
7012 QualType IVQT = IvarDecl->getType();
7013 if (IvarDecl->isBitField())
7014 IVQT = RewriteObj.GetGroupRecordTypeForObjCIvarBitfield(IvarDecl);
7015
Fariborz Jahanianae932952012-02-10 20:47:10 +00007016 std::string IvarTypeString, QuoteIvarTypeString;
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00007017 Context->getObjCEncodingForType(IVQT, IvarTypeString,
Fariborz Jahanianae932952012-02-10 20:47:10 +00007018 IvarDecl);
7019 RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString);
7020 Result += "\""; Result += QuoteIvarTypeString; Result += "\", ";
7021
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00007022 // FIXME. this alignment represents the host alignment and need be changed to
7023 // represent the target alignment.
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00007024 unsigned Align = Context->getTypeAlign(IVQT)/8;
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00007025 Align = llvm::Log2_32(Align);
Fariborz Jahanianae932952012-02-10 20:47:10 +00007026 Result += llvm::utostr(Align); Result += ", ";
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00007027 CharUnits Size = Context->getTypeSizeInChars(IVQT);
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00007028 Result += llvm::utostr(Size.getQuantity());
Fariborz Jahanianae932952012-02-10 20:47:10 +00007029 if (i == e-1)
7030 Result += "}}\n";
7031 else
7032 Result += "},\n";
7033 }
7034 Result += "};\n";
7035 }
7036}
7037
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007038/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00007039void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl,
7040 std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007041
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007042 // Do not synthesize the protocol more than once.
7043 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
7044 return;
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00007045 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007046
7047 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
7048 PDecl = Def;
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00007049 // Must write out all protocol definitions in current qualifier list,
7050 // and in their nested qualifiers before writing out current definition.
7051 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
7052 E = PDecl->protocol_end(); I != E; ++I)
7053 RewriteObjCProtocolMetaData(*I, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007054
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00007055 // Construct method lists.
7056 std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
7057 std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
7058 for (ObjCProtocolDecl::instmeth_iterator
7059 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
7060 I != E; ++I) {
7061 ObjCMethodDecl *MD = *I;
7062 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
7063 OptInstanceMethods.push_back(MD);
7064 } else {
7065 InstanceMethods.push_back(MD);
7066 }
7067 }
7068
7069 for (ObjCProtocolDecl::classmeth_iterator
7070 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
7071 I != E; ++I) {
7072 ObjCMethodDecl *MD = *I;
7073 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
7074 OptClassMethods.push_back(MD);
7075 } else {
7076 ClassMethods.push_back(MD);
7077 }
7078 }
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00007079 std::vector<ObjCMethodDecl *> AllMethods;
7080 for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++)
7081 AllMethods.push_back(InstanceMethods[i]);
7082 for (unsigned i = 0, e = ClassMethods.size(); i < e; i++)
7083 AllMethods.push_back(ClassMethods[i]);
7084 for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++)
7085 AllMethods.push_back(OptInstanceMethods[i]);
7086 for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++)
7087 AllMethods.push_back(OptClassMethods[i]);
7088
7089 Write__extendedMethodTypes_initializer(*this, Context, Result,
7090 AllMethods,
7091 "_OBJC_PROTOCOL_METHOD_TYPES_",
7092 PDecl->getNameAsString());
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00007093 // Protocol's super protocol list
7094 std::vector<ObjCProtocolDecl *> SuperProtocols;
7095 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
7096 E = PDecl->protocol_end(); I != E; ++I)
7097 SuperProtocols.push_back(*I);
7098
7099 Write_protocol_list_initializer(Context, Result, SuperProtocols,
7100 "_OBJC_PROTOCOL_REFS_",
7101 PDecl->getNameAsString());
7102
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007103 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00007104 "_OBJC_PROTOCOL_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007105 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00007106
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007107 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00007108 "_OBJC_PROTOCOL_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007109 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00007110
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007111 Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00007112 "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007113 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00007114
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007115 Write_method_list_t_initializer(*this, Context, Result, OptClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00007116 "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007117 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00007118
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00007119 // Protocol's property metadata.
7120 std::vector<ObjCPropertyDecl *> ProtocolProperties;
7121 for (ObjCContainerDecl::prop_iterator I = PDecl->prop_begin(),
7122 E = PDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00007123 ProtocolProperties.push_back(*I);
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00007124
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007125 Write_prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00007126 /* Container */0,
7127 "_OBJC_PROTOCOL_PROPERTIES_",
7128 PDecl->getNameAsString());
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00007129
Fariborz Jahanian82848c22012-02-08 00:50:52 +00007130 // Writer out root metadata for current protocol: struct _protocol_t
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007131 Result += "\n";
7132 if (LangOpts.MicrosoftExt)
Fariborz Jahanian8590d862012-04-14 17:13:08 +00007133 Result += "static ";
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00007134 Result += "struct _protocol_t _OBJC_PROTOCOL_";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007135 Result += PDecl->getNameAsString();
Fariborz Jahanian82848c22012-02-08 00:50:52 +00007136 Result += " __attribute__ ((used, section (\"__DATA,__datacoal_nt,coalesced\"))) = {\n";
7137 Result += "\t0,\n"; // id is; is null
7138 Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n";
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00007139 if (SuperProtocols.size() > 0) {
7140 Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_";
7141 Result += PDecl->getNameAsString(); Result += ",\n";
7142 }
7143 else
7144 Result += "\t0,\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00007145 if (InstanceMethods.size() > 0) {
7146 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
7147 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007148 }
7149 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00007150 Result += "\t0,\n";
7151
7152 if (ClassMethods.size() > 0) {
7153 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_";
7154 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007155 }
7156 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00007157 Result += "\t0,\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007158
Fariborz Jahanian82848c22012-02-08 00:50:52 +00007159 if (OptInstanceMethods.size() > 0) {
7160 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_";
7161 Result += PDecl->getNameAsString(); Result += ",\n";
7162 }
7163 else
7164 Result += "\t0,\n";
7165
7166 if (OptClassMethods.size() > 0) {
7167 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_";
7168 Result += PDecl->getNameAsString(); Result += ",\n";
7169 }
7170 else
7171 Result += "\t0,\n";
7172
7173 if (ProtocolProperties.size() > 0) {
7174 Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_";
7175 Result += PDecl->getNameAsString(); Result += ",\n";
7176 }
7177 else
7178 Result += "\t0,\n";
7179
7180 Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n";
7181 Result += "\t0,\n";
7182
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00007183 if (AllMethods.size() > 0) {
7184 Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_";
7185 Result += PDecl->getNameAsString();
7186 Result += "\n};\n";
7187 }
7188 else
7189 Result += "\t0\n};\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00007190
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00007191 if (LangOpts.MicrosoftExt)
Fariborz Jahanian8590d862012-04-14 17:13:08 +00007192 Result += "static ";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00007193 Result += "struct _protocol_t *";
7194 Result += "_OBJC_LABEL_PROTOCOL_$_"; Result += PDecl->getNameAsString();
7195 Result += " = &_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
7196 Result += ";\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00007197
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007198 // Mark this protocol as having been generated.
7199 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()))
7200 llvm_unreachable("protocol already synthesized");
7201
7202}
7203
7204void RewriteModernObjC::RewriteObjCProtocolListMetaData(
7205 const ObjCList<ObjCProtocolDecl> &Protocols,
7206 StringRef prefix, StringRef ClassName,
7207 std::string &Result) {
7208 if (Protocols.empty()) return;
7209
7210 for (unsigned i = 0; i != Protocols.size(); i++)
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00007211 RewriteObjCProtocolMetaData(Protocols[i], Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007212
7213 // Output the top lovel protocol meta-data for the class.
7214 /* struct _objc_protocol_list {
7215 struct _objc_protocol_list *next;
7216 int protocol_count;
7217 struct _objc_protocol *class_protocols[];
7218 }
7219 */
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007220 Result += "\n";
7221 if (LangOpts.MicrosoftExt)
7222 Result += "__declspec(allocate(\".cat_cls_meth$B\")) ";
7223 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007224 Result += "\tstruct _objc_protocol_list *next;\n";
7225 Result += "\tint protocol_count;\n";
7226 Result += "\tstruct _objc_protocol *class_protocols[";
7227 Result += utostr(Protocols.size());
7228 Result += "];\n} _OBJC_";
7229 Result += prefix;
7230 Result += "_PROTOCOLS_";
7231 Result += ClassName;
7232 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
7233 "{\n\t0, ";
7234 Result += utostr(Protocols.size());
7235 Result += "\n";
7236
7237 Result += "\t,{&_OBJC_PROTOCOL_";
7238 Result += Protocols[0]->getNameAsString();
7239 Result += " \n";
7240
7241 for (unsigned i = 1; i != Protocols.size(); i++) {
7242 Result += "\t ,&_OBJC_PROTOCOL_";
7243 Result += Protocols[i]->getNameAsString();
7244 Result += "\n";
7245 }
7246 Result += "\t }\n};\n";
7247}
7248
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00007249/// hasObjCExceptionAttribute - Return true if this class or any super
7250/// class has the __objc_exception__ attribute.
7251/// FIXME. Move this to ASTContext.cpp as it is also used for IRGen.
7252static bool hasObjCExceptionAttribute(ASTContext &Context,
7253 const ObjCInterfaceDecl *OID) {
7254 if (OID->hasAttr<ObjCExceptionAttr>())
7255 return true;
7256 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
7257 return hasObjCExceptionAttribute(Context, Super);
7258 return false;
7259}
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007260
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007261void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
7262 std::string &Result) {
7263 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7264
7265 // Explicitly declared @interface's are already synthesized.
Fariborz Jahanianae932952012-02-10 20:47:10 +00007266 if (CDecl->isImplicitInterfaceDecl())
7267 assert(false &&
7268 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00007269
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00007270 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanianae932952012-02-10 20:47:10 +00007271 SmallVector<ObjCIvarDecl *, 8> IVars;
7272
7273 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7274 IVD; IVD = IVD->getNextIvar()) {
7275 // Ignore unnamed bit-fields.
7276 if (!IVD->getDeclName())
7277 continue;
7278 IVars.push_back(IVD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007279 }
7280
Fariborz Jahanianae932952012-02-10 20:47:10 +00007281 Write__ivar_list_t_initializer(*this, Context, Result, IVars,
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007282 "_OBJC_$_INSTANCE_VARIABLES_",
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00007283 CDecl);
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007284
7285 // Build _objc_method_list for class's instance methods if needed
7286 SmallVector<ObjCMethodDecl *, 32>
7287 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
7288
7289 // If any of our property implementations have associated getters or
7290 // setters, produce metadata for them as well.
7291 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
7292 PropEnd = IDecl->propimpl_end();
7293 Prop != PropEnd; ++Prop) {
David Blaikie262bc182012-04-30 02:36:29 +00007294 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007295 continue;
David Blaikie262bc182012-04-30 02:36:29 +00007296 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007297 continue;
David Blaikie262bc182012-04-30 02:36:29 +00007298 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007299 if (!PD)
7300 continue;
7301 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
Fariborz Jahanian301e2e42012-05-03 22:52:13 +00007302 if (mustSynthesizeSetterGetterMethod(IDecl, PD, true /*getter*/))
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007303 InstanceMethods.push_back(Getter);
7304 if (PD->isReadOnly())
7305 continue;
7306 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
Fariborz Jahanian301e2e42012-05-03 22:52:13 +00007307 if (mustSynthesizeSetterGetterMethod(IDecl, PD, false /*setter*/))
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007308 InstanceMethods.push_back(Setter);
7309 }
7310
7311 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7312 "_OBJC_$_INSTANCE_METHODS_",
7313 IDecl->getNameAsString(), true);
7314
7315 SmallVector<ObjCMethodDecl *, 32>
7316 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
7317
7318 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7319 "_OBJC_$_CLASS_METHODS_",
7320 IDecl->getNameAsString(), true);
Fariborz Jahanian0a525342012-02-14 19:31:35 +00007321
7322 // Protocols referenced in class declaration?
7323 // Protocol's super protocol list
7324 std::vector<ObjCProtocolDecl *> RefedProtocols;
7325 const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols();
7326 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
7327 E = Protocols.end();
7328 I != E; ++I) {
7329 RefedProtocols.push_back(*I);
7330 // Must write out all protocol definitions in current qualifier list,
7331 // and in their nested qualifiers before writing out current definition.
7332 RewriteObjCProtocolMetaData(*I, Result);
7333 }
7334
7335 Write_protocol_list_initializer(Context, Result,
7336 RefedProtocols,
7337 "_OBJC_CLASS_PROTOCOLS_$_",
7338 IDecl->getNameAsString());
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007339
7340 // Protocol's property metadata.
7341 std::vector<ObjCPropertyDecl *> ClassProperties;
7342 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
7343 E = CDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00007344 ClassProperties.push_back(*I);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007345
7346 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahanian2df089d2012-03-22 17:39:35 +00007347 /* Container */IDecl,
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00007348 "_OBJC_$_PROP_LIST_",
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007349 CDecl->getNameAsString());
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007350
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007351
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00007352 // Data for initializing _class_ro_t metaclass meta-data
7353 uint32_t flags = CLS_META;
7354 std::string InstanceSize;
7355 std::string InstanceStart;
7356
7357
7358 bool classIsHidden = CDecl->getVisibility() == HiddenVisibility;
7359 if (classIsHidden)
7360 flags |= OBJC2_CLS_HIDDEN;
7361
7362 if (!CDecl->getSuperClass())
7363 // class is root
7364 flags |= CLS_ROOT;
7365 InstanceSize = "sizeof(struct _class_t)";
7366 InstanceStart = InstanceSize;
7367 Write__class_ro_t_initializer(Context, Result, flags,
7368 InstanceStart, InstanceSize,
7369 ClassMethods,
7370 0,
7371 0,
7372 0,
7373 "_OBJC_METACLASS_RO_$_",
7374 CDecl->getNameAsString());
7375
7376
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007377 // Data for initializing _class_ro_t meta-data
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00007378 flags = CLS;
7379 if (classIsHidden)
7380 flags |= OBJC2_CLS_HIDDEN;
7381
7382 if (hasObjCExceptionAttribute(*Context, CDecl))
7383 flags |= CLS_EXCEPTION;
7384
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007385 if (!CDecl->getSuperClass())
7386 // class is root
7387 flags |= CLS_ROOT;
7388
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00007389 InstanceSize.clear();
7390 InstanceStart.clear();
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007391 if (!ObjCSynthesizedStructs.count(CDecl)) {
7392 InstanceSize = "0";
7393 InstanceStart = "0";
7394 }
7395 else {
7396 InstanceSize = "sizeof(struct ";
7397 InstanceSize += CDecl->getNameAsString();
7398 InstanceSize += "_IMPL)";
7399
7400 ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7401 if (IVD) {
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00007402 RewriteIvarOffsetComputation(IVD, InstanceStart);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007403 }
7404 else
7405 InstanceStart = InstanceSize;
7406 }
7407 Write__class_ro_t_initializer(Context, Result, flags,
7408 InstanceStart, InstanceSize,
7409 InstanceMethods,
7410 RefedProtocols,
7411 IVars,
7412 ClassProperties,
7413 "_OBJC_CLASS_RO_$_",
7414 CDecl->getNameAsString());
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00007415
7416 Write_class_t(Context, Result,
7417 "OBJC_METACLASS_$_",
7418 CDecl, /*metaclass*/true);
7419
7420 Write_class_t(Context, Result,
7421 "OBJC_CLASS_$_",
7422 CDecl, /*metaclass*/false);
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007423
7424 if (ImplementationIsNonLazy(IDecl))
7425 DefinedNonLazyClasses.push_back(CDecl);
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00007426
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007427}
7428
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007429void RewriteModernObjC::RewriteClassSetupInitHook(std::string &Result) {
7430 int ClsDefCount = ClassImplementation.size();
7431 if (!ClsDefCount)
7432 return;
7433 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7434 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7435 Result += "static void *OBJC_CLASS_SETUP[] = {\n";
7436 for (int i = 0; i < ClsDefCount; i++) {
7437 ObjCImplementationDecl *IDecl = ClassImplementation[i];
7438 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7439 Result += "\t(void *)&OBJC_CLASS_SETUP_$_";
7440 Result += CDecl->getName(); Result += ",\n";
7441 }
7442 Result += "};\n";
7443}
7444
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007445void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
7446 int ClsDefCount = ClassImplementation.size();
7447 int CatDefCount = CategoryImplementation.size();
7448
7449 // For each implemented class, write out all its meta data.
7450 for (int i = 0; i < ClsDefCount; i++)
7451 RewriteObjCClassMetaData(ClassImplementation[i], Result);
7452
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007453 RewriteClassSetupInitHook(Result);
7454
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007455 // For each implemented category, write out all its meta data.
7456 for (int i = 0; i < CatDefCount; i++)
7457 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
7458
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007459 RewriteCategorySetupInitHook(Result);
7460
Fariborz Jahaniandf795672012-02-17 00:06:14 +00007461 if (ClsDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007462 if (LangOpts.MicrosoftExt)
7463 Result += "__declspec(allocate(\".objc_classlist$B\")) ";
Fariborz Jahaniandf795672012-02-17 00:06:14 +00007464 Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ [";
7465 Result += llvm::utostr(ClsDefCount); Result += "]";
7466 Result +=
7467 " __attribute__((used, section (\"__DATA, __objc_classlist,"
7468 "regular,no_dead_strip\")))= {\n";
7469 for (int i = 0; i < ClsDefCount; i++) {
7470 Result += "\t&OBJC_CLASS_$_";
7471 Result += ClassImplementation[i]->getNameAsString();
7472 Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007473 }
Fariborz Jahaniandf795672012-02-17 00:06:14 +00007474 Result += "};\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007475
7476 if (!DefinedNonLazyClasses.empty()) {
7477 if (LangOpts.MicrosoftExt)
7478 Result += "__declspec(allocate(\".objc_nlclslist$B\")) \n";
7479 Result += "static struct _class_t *_OBJC_LABEL_NONLAZY_CLASS_$[] = {\n\t";
7480 for (unsigned i = 0, e = DefinedNonLazyClasses.size(); i < e; i++) {
7481 Result += "\t&OBJC_CLASS_$_"; Result += DefinedNonLazyClasses[i]->getNameAsString();
7482 Result += ",\n";
7483 }
7484 Result += "};\n";
7485 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007486 }
Fariborz Jahanian61186122012-02-17 18:40:41 +00007487
7488 if (CatDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007489 if (LangOpts.MicrosoftExt)
7490 Result += "__declspec(allocate(\".objc_catlist$B\")) ";
Fariborz Jahanian61186122012-02-17 18:40:41 +00007491 Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [";
7492 Result += llvm::utostr(CatDefCount); Result += "]";
7493 Result +=
7494 " __attribute__((used, section (\"__DATA, __objc_catlist,"
7495 "regular,no_dead_strip\")))= {\n";
7496 for (int i = 0; i < CatDefCount; i++) {
7497 Result += "\t&_OBJC_$_CATEGORY_";
7498 Result +=
7499 CategoryImplementation[i]->getClassInterface()->getNameAsString();
7500 Result += "_$_";
7501 Result += CategoryImplementation[i]->getNameAsString();
7502 Result += ",\n";
7503 }
7504 Result += "};\n";
7505 }
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007506
7507 if (!DefinedNonLazyCategories.empty()) {
7508 if (LangOpts.MicrosoftExt)
7509 Result += "__declspec(allocate(\".objc_nlcatlist$B\")) \n";
7510 Result += "static struct _category_t *_OBJC_LABEL_NONLAZY_CATEGORY_$[] = {\n\t";
7511 for (unsigned i = 0, e = DefinedNonLazyCategories.size(); i < e; i++) {
7512 Result += "\t&_OBJC_$_CATEGORY_";
7513 Result +=
7514 DefinedNonLazyCategories[i]->getClassInterface()->getNameAsString();
7515 Result += "_$_";
7516 Result += DefinedNonLazyCategories[i]->getNameAsString();
7517 Result += ",\n";
7518 }
7519 Result += "};\n";
7520 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007521}
7522
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00007523void RewriteModernObjC::WriteImageInfo(std::string &Result) {
7524 if (LangOpts.MicrosoftExt)
7525 Result += "__declspec(allocate(\".objc_imageinfo$B\")) \n";
7526
7527 Result += "static struct IMAGE_INFO { unsigned version; unsigned flag; } ";
7528 // version 0, ObjCABI is 2
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00007529 Result += "_OBJC_IMAGE_INFO = { 0, 2 };\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00007530}
7531
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007532/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
7533/// implementation.
7534void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
7535 std::string &Result) {
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00007536 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007537 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7538 // Find category declaration for this implementation.
Douglas Gregord3297242013-01-16 23:00:23 +00007539 ObjCCategoryDecl *CDecl
7540 = ClassDecl->FindCategoryDeclaration(IDecl->getIdentifier());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007541
7542 std::string FullCategoryName = ClassDecl->getNameAsString();
Fariborz Jahanian61186122012-02-17 18:40:41 +00007543 FullCategoryName += "_$_";
7544 FullCategoryName += CDecl->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007545
7546 // Build _objc_method_list for class's instance methods if needed
7547 SmallVector<ObjCMethodDecl *, 32>
7548 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
7549
7550 // If any of our property implementations have associated getters or
7551 // setters, produce metadata for them as well.
7552 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
7553 PropEnd = IDecl->propimpl_end();
7554 Prop != PropEnd; ++Prop) {
David Blaikie262bc182012-04-30 02:36:29 +00007555 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007556 continue;
David Blaikie262bc182012-04-30 02:36:29 +00007557 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007558 continue;
David Blaikie262bc182012-04-30 02:36:29 +00007559 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007560 if (!PD)
7561 continue;
7562 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
7563 InstanceMethods.push_back(Getter);
7564 if (PD->isReadOnly())
7565 continue;
7566 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
7567 InstanceMethods.push_back(Setter);
7568 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007569
Fariborz Jahanian61186122012-02-17 18:40:41 +00007570 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7571 "_OBJC_$_CATEGORY_INSTANCE_METHODS_",
7572 FullCategoryName, true);
7573
7574 SmallVector<ObjCMethodDecl *, 32>
7575 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
7576
7577 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7578 "_OBJC_$_CATEGORY_CLASS_METHODS_",
7579 FullCategoryName, true);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007580
7581 // Protocols referenced in class declaration?
Fariborz Jahanian61186122012-02-17 18:40:41 +00007582 // Protocol's super protocol list
7583 std::vector<ObjCProtocolDecl *> RefedProtocols;
Argyrios Kyrtzidisa5f44412012-03-13 01:09:41 +00007584 for (ObjCInterfaceDecl::protocol_iterator I = CDecl->protocol_begin(),
7585 E = CDecl->protocol_end();
7586
7587 I != E; ++I) {
Fariborz Jahanian61186122012-02-17 18:40:41 +00007588 RefedProtocols.push_back(*I);
7589 // Must write out all protocol definitions in current qualifier list,
7590 // and in their nested qualifiers before writing out current definition.
7591 RewriteObjCProtocolMetaData(*I, Result);
7592 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007593
Fariborz Jahanian61186122012-02-17 18:40:41 +00007594 Write_protocol_list_initializer(Context, Result,
7595 RefedProtocols,
7596 "_OBJC_CATEGORY_PROTOCOLS_$_",
7597 FullCategoryName);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007598
Fariborz Jahanian61186122012-02-17 18:40:41 +00007599 // Protocol's property metadata.
7600 std::vector<ObjCPropertyDecl *> ClassProperties;
7601 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
7602 E = CDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00007603 ClassProperties.push_back(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007604
Fariborz Jahanian61186122012-02-17 18:40:41 +00007605 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahanianebfa2722012-05-03 23:19:33 +00007606 /* Container */IDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00007607 "_OBJC_$_PROP_LIST_",
7608 FullCategoryName);
7609
7610 Write_category_t(*this, Context, Result,
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007611 CDecl,
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007612 ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00007613 InstanceMethods,
7614 ClassMethods,
7615 RefedProtocols,
7616 ClassProperties);
7617
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007618 // Determine if this category is also "non-lazy".
7619 if (ImplementationIsNonLazy(IDecl))
7620 DefinedNonLazyCategories.push_back(CDecl);
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007621
7622}
7623
7624void RewriteModernObjC::RewriteCategorySetupInitHook(std::string &Result) {
7625 int CatDefCount = CategoryImplementation.size();
7626 if (!CatDefCount)
7627 return;
7628 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7629 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7630 Result += "static void *OBJC_CATEGORY_SETUP[] = {\n";
7631 for (int i = 0; i < CatDefCount; i++) {
7632 ObjCCategoryImplDecl *IDecl = CategoryImplementation[i];
7633 ObjCCategoryDecl *CatDecl= IDecl->getCategoryDecl();
7634 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7635 Result += "\t(void *)&OBJC_CATEGORY_SETUP_$_";
7636 Result += ClassDecl->getName();
7637 Result += "_$_";
7638 Result += CatDecl->getName();
7639 Result += ",\n";
7640 }
7641 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007642}
7643
7644// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
7645/// class methods.
7646template<typename MethodIterator>
7647void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
7648 MethodIterator MethodEnd,
7649 bool IsInstanceMethod,
7650 StringRef prefix,
7651 StringRef ClassName,
7652 std::string &Result) {
7653 if (MethodBegin == MethodEnd) return;
7654
7655 if (!objc_impl_method) {
7656 /* struct _objc_method {
7657 SEL _cmd;
7658 char *method_types;
7659 void *_imp;
7660 }
7661 */
7662 Result += "\nstruct _objc_method {\n";
7663 Result += "\tSEL _cmd;\n";
7664 Result += "\tchar *method_types;\n";
7665 Result += "\tvoid *_imp;\n";
7666 Result += "};\n";
7667
7668 objc_impl_method = true;
7669 }
7670
7671 // Build _objc_method_list for class's methods if needed
7672
7673 /* struct {
7674 struct _objc_method_list *next_method;
7675 int method_count;
7676 struct _objc_method method_list[];
7677 }
7678 */
7679 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007680 Result += "\n";
7681 if (LangOpts.MicrosoftExt) {
7682 if (IsInstanceMethod)
7683 Result += "__declspec(allocate(\".inst_meth$B\")) ";
7684 else
7685 Result += "__declspec(allocate(\".cls_meth$B\")) ";
7686 }
7687 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007688 Result += "\tstruct _objc_method_list *next_method;\n";
7689 Result += "\tint method_count;\n";
7690 Result += "\tstruct _objc_method method_list[";
7691 Result += utostr(NumMethods);
7692 Result += "];\n} _OBJC_";
7693 Result += prefix;
7694 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
7695 Result += "_METHODS_";
7696 Result += ClassName;
7697 Result += " __attribute__ ((used, section (\"__OBJC, __";
7698 Result += IsInstanceMethod ? "inst" : "cls";
7699 Result += "_meth\")))= ";
7700 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
7701
7702 Result += "\t,{{(SEL)\"";
7703 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7704 std::string MethodTypeString;
7705 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7706 Result += "\", \"";
7707 Result += MethodTypeString;
7708 Result += "\", (void *)";
7709 Result += MethodInternalNames[*MethodBegin];
7710 Result += "}\n";
7711 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
7712 Result += "\t ,{(SEL)\"";
7713 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7714 std::string MethodTypeString;
7715 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7716 Result += "\", \"";
7717 Result += MethodTypeString;
7718 Result += "\", (void *)";
7719 Result += MethodInternalNames[*MethodBegin];
7720 Result += "}\n";
7721 }
7722 Result += "\t }\n};\n";
7723}
7724
7725Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
7726 SourceRange OldRange = IV->getSourceRange();
7727 Expr *BaseExpr = IV->getBase();
7728
7729 // Rewrite the base, but without actually doing replaces.
7730 {
7731 DisableReplaceStmtScope S(*this);
7732 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
7733 IV->setBase(BaseExpr);
7734 }
7735
7736 ObjCIvarDecl *D = IV->getDecl();
7737
7738 Expr *Replacement = IV;
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007739
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007740 if (BaseExpr->getType()->isObjCObjectPointerType()) {
7741 const ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +00007742 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007743 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
7744 // lookup which class implements the instance variable.
7745 ObjCInterfaceDecl *clsDeclared = 0;
7746 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
7747 clsDeclared);
7748 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
7749
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007750 // Build name of symbol holding ivar offset.
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00007751 std::string IvarOffsetName;
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00007752 if (D->isBitField())
7753 ObjCIvarBitfieldGroupOffset(D, IvarOffsetName);
7754 else
7755 WriteInternalIvarName(clsDeclared, D, IvarOffsetName);
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00007756
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00007757 ReferencedIvars[clsDeclared].insert(D);
7758
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007759 // cast offset to "char *".
7760 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context,
7761 Context->getPointerType(Context->CharTy),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007762 CK_BitCast,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007763 BaseExpr);
7764 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
7765 SourceLocation(), &Context->Idents.get(IvarOffsetName),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00007766 Context->UnsignedLongTy, 0, SC_Extern);
John McCallf4b88a42012-03-10 09:33:50 +00007767 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false,
7768 Context->UnsignedLongTy, VK_LValue,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007769 SourceLocation());
7770 BinaryOperator *addExpr =
7771 new (Context) BinaryOperator(castExpr, DRE, BO_Add,
7772 Context->getPointerType(Context->CharTy),
Lang Hamesbe9af122012-10-02 04:45:10 +00007773 VK_RValue, OK_Ordinary, SourceLocation(), false);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007774 // Don't forget the parens to enforce the proper binding.
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007775 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(),
7776 SourceLocation(),
7777 addExpr);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00007778 QualType IvarT = D->getType();
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00007779 if (D->isBitField())
7780 IvarT = GetGroupRecordTypeForObjCIvarBitfield(D);
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007781
Fariborz Jahanianf5eac482012-05-02 17:34:59 +00007782 if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007783 RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00007784 RD = RD->getDefinition();
7785 if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007786 // decltype(((Foo_IMPL*)0)->bar) *
Fariborz Jahanianf5eac482012-05-02 17:34:59 +00007787 ObjCContainerDecl *CDecl =
7788 dyn_cast<ObjCContainerDecl>(D->getDeclContext());
7789 // ivar in class extensions requires special treatment.
7790 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
7791 CDecl = CatDecl->getClassInterface();
7792 std::string RecName = CDecl->getName();
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007793 RecName += "_IMPL";
7794 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
7795 SourceLocation(), SourceLocation(),
7796 &Context->Idents.get(RecName.c_str()));
7797 QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
7798 unsigned UnsignedIntSize =
7799 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
7800 Expr *Zero = IntegerLiteral::Create(*Context,
7801 llvm::APInt(UnsignedIntSize, 0),
7802 Context->UnsignedIntTy, SourceLocation());
7803 Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
7804 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
7805 Zero);
7806 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
7807 SourceLocation(),
7808 &Context->Idents.get(D->getNameAsString()),
7809 IvarT, 0,
7810 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00007811 ICIS_NoInit);
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007812 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
7813 FD->getType(), VK_LValue,
7814 OK_Ordinary);
7815 IvarT = Context->getDecltypeType(ME, ME->getType());
7816 }
7817 }
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00007818 convertObjCTypeToCStyleType(IvarT);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00007819 QualType castT = Context->getPointerType(IvarT);
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007820
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007821 castExpr = NoTypeInfoCStyleCastExpr(Context,
7822 castT,
7823 CK_BitCast,
7824 PE);
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007825
7826
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00007827 Expr *Exp = new (Context) UnaryOperator(castExpr, UO_Deref, IvarT,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007828 VK_LValue, OK_Ordinary,
7829 SourceLocation());
7830 PE = new (Context) ParenExpr(OldRange.getBegin(),
7831 OldRange.getEnd(),
7832 Exp);
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00007833
7834 if (D->isBitField()) {
7835 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
7836 SourceLocation(),
7837 &Context->Idents.get(D->getNameAsString()),
7838 D->getType(), 0,
7839 /*BitWidth=*/D->getBitWidth(),
7840 /*Mutable=*/true,
7841 ICIS_NoInit);
7842 MemberExpr *ME = new (Context) MemberExpr(PE, /*isArrow*/false, FD, SourceLocation(),
7843 FD->getType(), VK_LValue,
7844 OK_Ordinary);
7845 Replacement = ME;
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007846
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00007847 }
7848 else
7849 Replacement = PE;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007850 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007851
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007852 ReplaceStmtWithRange(IV, Replacement, OldRange);
7853 return Replacement;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007854}