blob: af9cda3faddf8b85910b013fb6f1bc7826938d17 [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 };
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000061
62 Rewriter Rewrite;
63 DiagnosticsEngine &Diags;
64 const LangOptions &LangOpts;
65 ASTContext *Context;
66 SourceManager *SM;
67 TranslationUnitDecl *TUDecl;
68 FileID MainFileID;
69 const char *MainFileStart, *MainFileEnd;
70 Stmt *CurrentBody;
71 ParentMap *PropParentMap; // created lazily.
72 std::string InFileName;
73 raw_ostream* OutFile;
74 std::string Preamble;
75
76 TypeDecl *ProtocolTypeDecl;
77 VarDecl *GlobalVarDecl;
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +000078 Expr *GlobalConstructionExp;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000079 unsigned RewriteFailedDiag;
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +000080 unsigned GlobalBlockRewriteFailedDiag;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000081 // ObjC string constant support.
82 unsigned NumObjCStringLiterals;
83 VarDecl *ConstantStringClassReference;
84 RecordDecl *NSStringRecord;
85
86 // ObjC foreach break/continue generation support.
87 int BcLabelCount;
88
89 unsigned TryFinallyContainsReturnDiag;
90 // Needed for super.
91 ObjCMethodDecl *CurMethodDef;
92 RecordDecl *SuperStructDecl;
93 RecordDecl *ConstantStringDecl;
94
95 FunctionDecl *MsgSendFunctionDecl;
96 FunctionDecl *MsgSendSuperFunctionDecl;
97 FunctionDecl *MsgSendStretFunctionDecl;
98 FunctionDecl *MsgSendSuperStretFunctionDecl;
99 FunctionDecl *MsgSendFpretFunctionDecl;
100 FunctionDecl *GetClassFunctionDecl;
101 FunctionDecl *GetMetaClassFunctionDecl;
102 FunctionDecl *GetSuperClassFunctionDecl;
103 FunctionDecl *SelGetUidFunctionDecl;
104 FunctionDecl *CFStringFunctionDecl;
Benjamin Kramere5753592013-09-09 14:48:42 +0000105 FunctionDecl *SuperConstructorFunctionDecl;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000106 FunctionDecl *CurFunctionDef;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000107
108 /* Misc. containers needed for meta-data rewrite. */
109 SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
110 SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
111 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
112 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000113 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCWrittenInterfaces;
Fariborz Jahanian8fba8942012-04-30 23:20:30 +0000114 llvm::SmallPtrSet<TagDecl*, 32> GlobalDefinedTags;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000115 SmallVector<ObjCInterfaceDecl*, 32> ObjCInterfacesSeen;
Fariborz Jahanian88f7f752012-03-14 23:18:19 +0000116 /// DefinedNonLazyClasses - List of defined "non-lazy" classes.
117 SmallVector<ObjCInterfaceDecl*, 8> DefinedNonLazyClasses;
118
119 /// DefinedNonLazyCategories - List of defined "non-lazy" categories.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000120 SmallVector<ObjCCategoryDecl *, 8> DefinedNonLazyCategories;
Fariborz Jahanian88f7f752012-03-14 23:18:19 +0000121
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000122 SmallVector<Stmt *, 32> Stmts;
123 SmallVector<int, 8> ObjCBcLabelNo;
124 // Remember all the @protocol(<expr>) expressions.
125 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
126
127 llvm::DenseSet<uint64_t> CopyDestroyCache;
128
129 // Block expressions.
130 SmallVector<BlockExpr *, 32> Blocks;
131 SmallVector<int, 32> InnerDeclRefsCount;
John McCallf4b88a42012-03-10 09:33:50 +0000132 SmallVector<DeclRefExpr *, 32> InnerDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000133
John McCallf4b88a42012-03-10 09:33:50 +0000134 SmallVector<DeclRefExpr *, 32> BlockDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000135
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +0000136
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000137 // Block related declarations.
138 SmallVector<ValueDecl *, 8> BlockByCopyDecls;
139 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
140 SmallVector<ValueDecl *, 8> BlockByRefDecls;
141 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
142 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
143 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
144 llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
145
146 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
Fariborz Jahanian72c88f12012-02-22 18:13:25 +0000147 llvm::DenseMap<ObjCInterfaceDecl *,
148 llvm::SmallPtrSet<ObjCIvarDecl *, 8> > ReferencedIvars;
149
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +0000150 // ivar bitfield grouping containers
151 llvm::DenseSet<const ObjCInterfaceDecl *> ObjCInterefaceHasBitfieldGroups;
152 llvm::DenseMap<const ObjCIvarDecl* , unsigned> IvarGroupNumber;
153 // This container maps an <class, group number for ivar> tuple to the type
154 // of the struct where the bitfield belongs.
155 llvm::DenseMap<std::pair<const ObjCInterfaceDecl*, unsigned>, QualType> GroupRecordType;
Fariborz Jahanian31c4a4b2013-02-07 22:50:40 +0000156 SmallVector<FunctionDecl*, 32> FunctionDefinitionsSeen;
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +0000157
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000158 // This maps an original source AST to it's rewritten form. This allows
159 // us to avoid rewriting the same node twice (which is very uncommon).
160 // This is needed to support some of the exotic property rewriting.
161 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
162
163 // Needed for header files being rewritten
164 bool IsHeader;
165 bool SilenceRewriteMacroWarning;
Fariborz Jahanianada71912013-02-08 00:27:34 +0000166 bool GenerateLineInfo;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000167 bool objc_impl_method;
168
169 bool DisableReplaceStmt;
170 class DisableReplaceStmtScope {
171 RewriteModernObjC &R;
172 bool SavedValue;
173
174 public:
175 DisableReplaceStmtScope(RewriteModernObjC &R)
176 : R(R), SavedValue(R.DisableReplaceStmt) {
177 R.DisableReplaceStmt = true;
178 }
179 ~DisableReplaceStmtScope() {
180 R.DisableReplaceStmt = SavedValue;
181 }
182 };
183 void InitializeCommon(ASTContext &context);
184
185 public:
Fariborz Jahanian90af4e22012-02-14 17:19:02 +0000186 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000187 // Top Level Driver code.
188 virtual bool HandleTopLevelDecl(DeclGroupRef D) {
189 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
190 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*I)) {
191 if (!Class->isThisDeclarationADefinition()) {
192 RewriteForwardClassDecl(D);
193 break;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000194 } else {
195 // Keep track of all interface declarations seen.
Fariborz Jahanianf3295272012-02-24 21:42:38 +0000196 ObjCInterfacesSeen.push_back(Class);
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000197 break;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000198 }
199 }
200
201 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*I)) {
202 if (!Proto->isThisDeclarationADefinition()) {
203 RewriteForwardProtocolDecl(D);
204 break;
205 }
206 }
207
Fariborz Jahanian31c4a4b2013-02-07 22:50:40 +0000208 if (FunctionDecl *FDecl = dyn_cast<FunctionDecl>(*I)) {
209 // Under modern abi, we cannot translate body of the function
210 // yet until all class extensions and its implementation is seen.
211 // This is because they may introduce new bitfields which must go
212 // into their grouping struct.
213 if (FDecl->isThisDeclarationADefinition() &&
214 // Not c functions defined inside an objc container.
215 !FDecl->isTopLevelDeclInObjCContainer()) {
216 FunctionDefinitionsSeen.push_back(FDecl);
217 break;
218 }
219 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000220 HandleTopLevelSingleDecl(*I);
221 }
222 return true;
223 }
224 void HandleTopLevelSingleDecl(Decl *D);
225 void HandleDeclInMainFile(Decl *D);
226 RewriteModernObjC(std::string inFile, raw_ostream *OS,
227 DiagnosticsEngine &D, const LangOptions &LOpts,
Fariborz Jahanianada71912013-02-08 00:27:34 +0000228 bool silenceMacroWarn, bool LineInfo);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000229
230 ~RewriteModernObjC() {}
231
232 virtual void HandleTranslationUnit(ASTContext &C);
233
234 void ReplaceStmt(Stmt *Old, Stmt *New) {
235 Stmt *ReplacingStmt = ReplacedNodes[Old];
236
237 if (ReplacingStmt)
238 return; // We can't rewrite the same node twice.
239
240 if (DisableReplaceStmt)
241 return;
242
243 // If replacement succeeded or warning disabled return with no warning.
244 if (!Rewrite.ReplaceStmt(Old, New)) {
245 ReplacedNodes[Old] = New;
246 return;
247 }
248 if (SilenceRewriteMacroWarning)
249 return;
250 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
251 << Old->getSourceRange();
252 }
253
254 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
255 if (DisableReplaceStmt)
256 return;
257
258 // Measure the old text.
259 int Size = Rewrite.getRangeSize(SrcRange);
260 if (Size == -1) {
261 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
262 << Old->getSourceRange();
263 return;
264 }
265 // Get the new text.
266 std::string SStr;
267 llvm::raw_string_ostream S(SStr);
Richard Smithd1420c62012-08-16 03:56:14 +0000268 New->printPretty(S, 0, PrintingPolicy(LangOpts));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000269 const std::string &Str = S.str();
270
271 // If replacement succeeded or warning disabled return with no warning.
272 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
273 ReplacedNodes[Old] = New;
274 return;
275 }
276 if (SilenceRewriteMacroWarning)
277 return;
278 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
279 << Old->getSourceRange();
280 }
281
282 void InsertText(SourceLocation Loc, StringRef Str,
283 bool InsertAfter = true) {
284 // If insertion succeeded or warning disabled return with no warning.
285 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
286 SilenceRewriteMacroWarning)
287 return;
288
289 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
290 }
291
292 void ReplaceText(SourceLocation Start, unsigned OrigLength,
293 StringRef Str) {
294 // If removal succeeded or warning disabled return with no warning.
295 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
296 SilenceRewriteMacroWarning)
297 return;
298
299 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
300 }
301
302 // Syntactic Rewriting.
303 void RewriteRecordBody(RecordDecl *RD);
304 void RewriteInclude();
Fariborz Jahanian96205962012-11-06 17:30:23 +0000305 void RewriteLineDirective(const Decl *D);
Fariborz Jahanianf616ae22012-11-06 23:25:49 +0000306 void ConvertSourceLocationToLineDirective(SourceLocation Loc,
307 std::string &LineString);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000308 void RewriteForwardClassDecl(DeclGroupRef D);
Craig Topper6b9240e2013-07-05 19:34:19 +0000309 void RewriteForwardClassDecl(const SmallVectorImpl<Decl *> &DG);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000310 void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
311 const std::string &typedefString);
312 void RewriteImplementations();
313 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
314 ObjCImplementationDecl *IMD,
315 ObjCCategoryImplDecl *CID);
316 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
317 void RewriteImplementationDecl(Decl *Dcl);
318 void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
319 ObjCMethodDecl *MDecl, std::string &ResultStr);
320 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
321 const FunctionType *&FPRetType);
322 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
323 ValueDecl *VD, bool def=false);
324 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
325 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
326 void RewriteForwardProtocolDecl(DeclGroupRef D);
Craig Topper6b9240e2013-07-05 19:34:19 +0000327 void RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000328 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
329 void RewriteProperty(ObjCPropertyDecl *prop);
330 void RewriteFunctionDecl(FunctionDecl *FD);
331 void RewriteBlockPointerType(std::string& Str, QualType Type);
332 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +0000333 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000334 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
335 void RewriteTypeOfDecl(VarDecl *VD);
336 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +0000337
338 std::string getIvarAccessString(ObjCIvarDecl *D);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000339
340 // Expression Rewriting.
341 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
342 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
343 Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
344 Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
345 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
346 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
347 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian55947042012-03-27 20:17:30 +0000348 Stmt *RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp);
Patrick Beardeb382ec2012-04-19 00:25:12 +0000349 Stmt *RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp);
Fariborz Jahanian86cff602012-03-30 23:35:47 +0000350 Stmt *RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +0000351 Stmt *RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000352 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000353 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahanian042b91d2012-05-23 23:47:20 +0000354 Stmt *RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000355 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
356 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
357 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
358 SourceLocation OrigEnd);
359 Stmt *RewriteBreakStmt(BreakStmt *S);
360 Stmt *RewriteContinueStmt(ContinueStmt *S);
361 void RewriteCastExpr(CStyleCastExpr *CE);
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +0000362 void RewriteImplicitCastObjCExpr(CastExpr *IE);
Fariborz Jahanianb3f904f2012-04-03 17:35:38 +0000363 void RewriteLinkageSpec(LinkageSpecDecl *LSD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000364
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +0000365 // Computes ivar bitfield group no.
366 unsigned ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV);
367 // Names field decl. for ivar bitfield group.
368 void ObjCIvarBitfieldGroupDecl(ObjCIvarDecl *IV, std::string &Result);
369 // Names struct type for ivar bitfield group.
370 void ObjCIvarBitfieldGroupType(ObjCIvarDecl *IV, std::string &Result);
371 // Names symbol for ivar bitfield group field offset.
372 void ObjCIvarBitfieldGroupOffset(ObjCIvarDecl *IV, std::string &Result);
373 // Given an ivar bitfield, it builds (or finds) its group record type.
374 QualType GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl *IV);
375 QualType SynthesizeBitfieldGroupStructType(
376 ObjCIvarDecl *IV,
377 SmallVectorImpl<ObjCIvarDecl *> &IVars);
378
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000379 // Block rewriting.
380 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
381
382 // Block specific rewrite rules.
383 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +0000384 void RewriteByRefVar(VarDecl *VD, bool firstDecl, bool lastDecl);
John McCallf4b88a42012-03-10 09:33:50 +0000385 Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000386 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
387 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
388
389 void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
390 std::string &Result);
391
Fariborz Jahanian15f87772012-02-28 22:45:07 +0000392 void RewriteObjCFieldDecl(FieldDecl *fieldDecl, std::string &Result);
Fariborz Jahanianb68258f2012-05-01 17:46:45 +0000393 bool IsTagDefinedInsideClass(ObjCContainerDecl *IDecl, TagDecl *Tag,
Fariborz Jahanian8fba8942012-04-30 23:20:30 +0000394 bool &IsNamedDefinition);
395 void RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
396 std::string &Result);
Fariborz Jahanian15f87772012-02-28 22:45:07 +0000397
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +0000398 bool RewriteObjCFieldDeclType(QualType &Type, std::string &Result);
399
Fariborz Jahanian72c88f12012-02-22 18:13:25 +0000400 void RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
401 std::string &Result);
402
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000403 virtual void Initialize(ASTContext &context);
404
Benjamin Kramer48d798c2012-06-02 10:20:41 +0000405 // Misc. AST transformation routines. Sometimes they end up calling
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000406 // rewriting routines on the new ASTs.
407 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
408 Expr **args, unsigned nargs,
409 SourceLocation StartLoc=SourceLocation(),
410 SourceLocation EndLoc=SourceLocation());
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +0000411
412 Expr *SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +0000413 QualType returnType,
414 SmallVectorImpl<QualType> &ArgTypes,
415 SmallVectorImpl<Expr*> &MsgExprs,
416 ObjCMethodDecl *Method);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000417
418 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
419 SourceLocation StartLoc=SourceLocation(),
420 SourceLocation EndLoc=SourceLocation());
421
422 void SynthCountByEnumWithState(std::string &buf);
423 void SynthMsgSendFunctionDecl();
424 void SynthMsgSendSuperFunctionDecl();
425 void SynthMsgSendStretFunctionDecl();
426 void SynthMsgSendFpretFunctionDecl();
427 void SynthMsgSendSuperStretFunctionDecl();
428 void SynthGetClassFunctionDecl();
429 void SynthGetMetaClassFunctionDecl();
430 void SynthGetSuperClassFunctionDecl();
431 void SynthSelGetUidFunctionDecl();
Benjamin Kramere5753592013-09-09 14:48:42 +0000432 void SynthSuperConstructorFunctionDecl();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000433
434 // Rewriting metadata
435 template<typename MethodIterator>
436 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
437 MethodIterator MethodEnd,
438 bool IsInstanceMethod,
439 StringRef prefix,
440 StringRef ClassName,
441 std::string &Result);
Fariborz Jahanianda9624a2012-02-08 19:53:58 +0000442 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
443 std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000444 void RewriteObjCProtocolListMetaData(
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000445 const ObjCList<ObjCProtocolDecl> &Prots,
446 StringRef prefix, StringRef ClassName, std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000447 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000448 std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000449 void RewriteClassSetupInitHook(std::string &Result);
Fariborz Jahaniane0335782012-03-27 18:41:05 +0000450
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000451 void RewriteMetaDataIntoBuffer(std::string &Result);
452 void WriteImageInfo(std::string &Result);
453 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000454 std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000455 void RewriteCategorySetupInitHook(std::string &Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000456
457 // Rewriting ivar
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000458 void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000459 std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000460 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000461
462
463 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
464 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
465 StringRef funcName, std::string Tag);
466 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
467 StringRef funcName, std::string Tag);
468 std::string SynthesizeBlockImpl(BlockExpr *CE,
469 std::string Tag, std::string Desc);
470 std::string SynthesizeBlockDescriptor(std::string DescTag,
471 std::string ImplTag,
472 int i, StringRef funcName,
473 unsigned hasCopy);
474 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
475 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
476 StringRef FunName);
477 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
478 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
Craig Topper6b9240e2013-07-05 19:34:19 +0000479 const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000480
481 // Misc. helper routines.
482 QualType getProtocolType();
483 void WarnAboutReturnGotoStmts(Stmt *S);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000484 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
485 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
486 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
487
488 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
489 void CollectBlockDeclRefInfo(BlockExpr *Exp);
490 void GetBlockDeclRefExprs(Stmt *S);
Craig Topper6b9240e2013-07-05 19:34:19 +0000491 void GetInnerBlockDeclRefExprs(Stmt *S,
492 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000493 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
494
495 // We avoid calling Type::isBlockPointerType(), since it operates on the
496 // canonical type. We only care if the top-level type is a closure pointer.
497 bool isTopLevelBlockPointerType(QualType T) {
498 return isa<BlockPointerType>(T);
499 }
500
501 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
502 /// to a function pointer type and upon success, returns true; false
503 /// otherwise.
504 bool convertBlockPointerToFunctionPointer(QualType &T) {
505 if (isTopLevelBlockPointerType(T)) {
506 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
507 T = Context->getPointerType(BPT->getPointeeType());
508 return true;
509 }
510 return false;
511 }
512
Fariborz Jahanian164d6f82012-02-13 18:57:49 +0000513 bool convertObjCTypeToCStyleType(QualType &T);
514
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000515 bool needToScanForQualifiers(QualType T);
516 QualType getSuperStructType();
517 QualType getConstantStringStructType();
518 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
519 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
520
521 void convertToUnqualifiedObjCType(QualType &T) {
Fariborz Jahaniane35abe12012-04-06 22:29:36 +0000522 if (T->isObjCQualifiedIdType()) {
523 bool isConst = T.isConstQualified();
524 T = isConst ? Context->getObjCIdType().withConst()
525 : Context->getObjCIdType();
526 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000527 else if (T->isObjCQualifiedClassType())
528 T = Context->getObjCClassType();
529 else if (T->isObjCObjectPointerType() &&
530 T->getPointeeType()->isObjCQualifiedInterfaceType()) {
531 if (const ObjCObjectPointerType * OBJPT =
532 T->getAsObjCInterfacePointerType()) {
533 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
534 T = QualType(IFaceT, 0);
535 T = Context->getPointerType(T);
536 }
537 }
538 }
539
540 // FIXME: This predicate seems like it would be useful to add to ASTContext.
541 bool isObjCType(QualType T) {
542 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
543 return false;
544
545 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
546
547 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
548 OCT == Context->getCanonicalType(Context->getObjCClassType()))
549 return true;
550
551 if (const PointerType *PT = OCT->getAs<PointerType>()) {
552 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
553 PT->getPointeeType()->isObjCQualifiedIdType())
554 return true;
555 }
556 return false;
557 }
558 bool PointerTypeTakesAnyBlockArguments(QualType QT);
559 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
560 void GetExtentOfArgList(const char *Name, const char *&LParen,
561 const char *&RParen);
562
563 void QuoteDoublequotes(std::string &From, std::string &To) {
564 for (unsigned i = 0; i < From.length(); i++) {
565 if (From[i] == '"')
566 To += "\\\"";
567 else
568 To += From[i];
569 }
570 }
571
572 QualType getSimpleFunctionType(QualType result,
Jordan Rosebea522f2013-03-08 21:51:21 +0000573 ArrayRef<QualType> args,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000574 bool variadic = false) {
575 if (result == Context->getObjCInstanceType())
576 result = Context->getObjCIdType();
577 FunctionProtoType::ExtProtoInfo fpi;
578 fpi.Variadic = variadic;
Jordan Rosebea522f2013-03-08 21:51:21 +0000579 return Context->getFunctionType(result, args, fpi);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000580 }
581
582 // Helper function: create a CStyleCastExpr with trivial type source info.
583 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
584 CastKind Kind, Expr *E) {
585 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
586 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, 0, TInfo,
587 SourceLocation(), SourceLocation());
588 }
Fariborz Jahanian88f7f752012-03-14 23:18:19 +0000589
590 bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const {
591 IdentifierInfo* II = &Context->Idents.get("load");
592 Selector LoadSel = Context->Selectors.getSelector(0, &II);
593 return OD->getClassMethod(LoadSel) != 0;
594 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000595 };
596
597}
598
599void RewriteModernObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
600 NamedDecl *D) {
601 if (const FunctionProtoType *fproto
602 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
603 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
604 E = fproto->arg_type_end(); I && (I != E); ++I)
605 if (isTopLevelBlockPointerType(*I)) {
606 // All the args are checked/rewritten. Don't call twice!
607 RewriteBlockPointerDecl(D);
608 break;
609 }
610 }
611}
612
613void RewriteModernObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
614 const PointerType *PT = funcType->getAs<PointerType>();
615 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
616 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
617}
618
619static bool IsHeaderFile(const std::string &Filename) {
620 std::string::size_type DotPos = Filename.rfind('.');
621
622 if (DotPos == std::string::npos) {
623 // no file extension
624 return false;
625 }
626
627 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
628 // C header: .h
629 // C++ header: .hh or .H;
630 return Ext == "h" || Ext == "hh" || Ext == "H";
631}
632
633RewriteModernObjC::RewriteModernObjC(std::string inFile, raw_ostream* OS,
634 DiagnosticsEngine &D, const LangOptions &LOpts,
Fariborz Jahanianada71912013-02-08 00:27:34 +0000635 bool silenceMacroWarn,
636 bool LineInfo)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000637 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
Fariborz Jahanianada71912013-02-08 00:27:34 +0000638 SilenceRewriteMacroWarning(silenceMacroWarn), GenerateLineInfo(LineInfo) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000639 IsHeader = IsHeaderFile(inFile);
640 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
641 "rewriting sub-expression within a macro (may not be correct)");
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +0000642 // FIXME. This should be an error. But if block is not called, it is OK. And it
643 // may break including some headers.
644 GlobalBlockRewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
645 "rewriting block literal declared in global scope is not implemented");
646
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000647 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
648 DiagnosticsEngine::Warning,
649 "rewriter doesn't support user-specified control flow semantics "
650 "for @try/@finally (code may not execute properly)");
651}
652
653ASTConsumer *clang::CreateModernObjCRewriter(const std::string& InFile,
654 raw_ostream* OS,
655 DiagnosticsEngine &Diags,
656 const LangOptions &LOpts,
Fariborz Jahanianada71912013-02-08 00:27:34 +0000657 bool SilenceRewriteMacroWarning,
658 bool LineInfo) {
659 return new RewriteModernObjC(InFile, OS, Diags, LOpts,
660 SilenceRewriteMacroWarning, LineInfo);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000661}
662
663void RewriteModernObjC::InitializeCommon(ASTContext &context) {
664 Context = &context;
665 SM = &Context->getSourceManager();
666 TUDecl = Context->getTranslationUnitDecl();
667 MsgSendFunctionDecl = 0;
668 MsgSendSuperFunctionDecl = 0;
669 MsgSendStretFunctionDecl = 0;
670 MsgSendSuperStretFunctionDecl = 0;
671 MsgSendFpretFunctionDecl = 0;
672 GetClassFunctionDecl = 0;
673 GetMetaClassFunctionDecl = 0;
674 GetSuperClassFunctionDecl = 0;
675 SelGetUidFunctionDecl = 0;
676 CFStringFunctionDecl = 0;
677 ConstantStringClassReference = 0;
678 NSStringRecord = 0;
679 CurMethodDef = 0;
680 CurFunctionDef = 0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000681 GlobalVarDecl = 0;
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +0000682 GlobalConstructionExp = 0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000683 SuperStructDecl = 0;
684 ProtocolTypeDecl = 0;
685 ConstantStringDecl = 0;
686 BcLabelCount = 0;
Benjamin Kramere5753592013-09-09 14:48:42 +0000687 SuperConstructorFunctionDecl = 0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000688 NumObjCStringLiterals = 0;
689 PropParentMap = 0;
690 CurrentBody = 0;
691 DisableReplaceStmt = false;
692 objc_impl_method = false;
693
694 // Get the ID and start/end of the main file.
695 MainFileID = SM->getMainFileID();
696 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
697 MainFileStart = MainBuf->getBufferStart();
698 MainFileEnd = MainBuf->getBufferEnd();
699
David Blaikie4e4d0842012-03-11 07:00:24 +0000700 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000701}
702
703//===----------------------------------------------------------------------===//
704// Top Level Driver Code
705//===----------------------------------------------------------------------===//
706
707void RewriteModernObjC::HandleTopLevelSingleDecl(Decl *D) {
708 if (Diags.hasErrorOccurred())
709 return;
710
711 // Two cases: either the decl could be in the main file, or it could be in a
712 // #included file. If the former, rewrite it now. If the later, check to see
713 // if we rewrote the #include/#import.
714 SourceLocation Loc = D->getLocation();
715 Loc = SM->getExpansionLoc(Loc);
716
717 // If this is for a builtin, ignore it.
718 if (Loc.isInvalid()) return;
719
720 // Look for built-in declarations that we need to refer during the rewrite.
721 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
722 RewriteFunctionDecl(FD);
723 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
724 // declared in <Foundation/NSString.h>
725 if (FVD->getName() == "_NSConstantStringClassReference") {
726 ConstantStringClassReference = FVD;
727 return;
728 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000729 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
730 RewriteCategoryDecl(CD);
731 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
732 if (PD->isThisDeclarationADefinition())
733 RewriteProtocolDecl(PD);
734 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
Fariborz Jahanian8e86b2d2012-04-04 17:16:15 +0000735 // FIXME. This will not work in all situations and leaving it out
736 // is harmless.
737 // RewriteLinkageSpec(LSD);
738
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000739 // Recurse into linkage specifications
740 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
741 DIEnd = LSD->decls_end();
742 DI != DIEnd; ) {
743 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
744 if (!IFace->isThisDeclarationADefinition()) {
745 SmallVector<Decl *, 8> DG;
746 SourceLocation StartLoc = IFace->getLocStart();
747 do {
748 if (isa<ObjCInterfaceDecl>(*DI) &&
749 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
750 StartLoc == (*DI)->getLocStart())
751 DG.push_back(*DI);
752 else
753 break;
754
755 ++DI;
756 } while (DI != DIEnd);
757 RewriteForwardClassDecl(DG);
758 continue;
759 }
Fariborz Jahanianb3f904f2012-04-03 17:35:38 +0000760 else {
761 // Keep track of all interface declarations seen.
762 ObjCInterfacesSeen.push_back(IFace);
763 ++DI;
764 continue;
765 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000766 }
767
768 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
769 if (!Proto->isThisDeclarationADefinition()) {
770 SmallVector<Decl *, 8> DG;
771 SourceLocation StartLoc = Proto->getLocStart();
772 do {
773 if (isa<ObjCProtocolDecl>(*DI) &&
774 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
775 StartLoc == (*DI)->getLocStart())
776 DG.push_back(*DI);
777 else
778 break;
779
780 ++DI;
781 } while (DI != DIEnd);
782 RewriteForwardProtocolDecl(DG);
783 continue;
784 }
785 }
786
787 HandleTopLevelSingleDecl(*DI);
788 ++DI;
789 }
790 }
791 // If we have a decl in the main file, see if we should rewrite it.
Eli Friedman24146972013-08-22 00:27:10 +0000792 if (SM->isWrittenInMainFile(Loc))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000793 return HandleDeclInMainFile(D);
794}
795
796//===----------------------------------------------------------------------===//
797// Syntactic (non-AST) Rewriting Code
798//===----------------------------------------------------------------------===//
799
800void RewriteModernObjC::RewriteInclude() {
801 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
802 StringRef MainBuf = SM->getBufferData(MainFileID);
803 const char *MainBufStart = MainBuf.begin();
804 const char *MainBufEnd = MainBuf.end();
805 size_t ImportLen = strlen("import");
806
807 // Loop over the whole file, looking for includes.
808 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
809 if (*BufPtr == '#') {
810 if (++BufPtr == MainBufEnd)
811 return;
812 while (*BufPtr == ' ' || *BufPtr == '\t')
813 if (++BufPtr == MainBufEnd)
814 return;
815 if (!strncmp(BufPtr, "import", ImportLen)) {
816 // replace import with include
817 SourceLocation ImportLoc =
818 LocStart.getLocWithOffset(BufPtr-MainBufStart);
819 ReplaceText(ImportLoc, ImportLen, "include");
820 BufPtr += ImportLen;
821 }
822 }
823 }
824}
825
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +0000826static void WriteInternalIvarName(const ObjCInterfaceDecl *IDecl,
827 ObjCIvarDecl *IvarDecl, std::string &Result) {
828 Result += "OBJC_IVAR_$_";
829 Result += IDecl->getName();
830 Result += "$";
831 Result += IvarDecl->getName();
832}
833
834std::string
835RewriteModernObjC::getIvarAccessString(ObjCIvarDecl *D) {
836 const ObjCInterfaceDecl *ClassDecl = D->getContainingInterface();
837
838 // Build name of symbol holding ivar offset.
839 std::string IvarOffsetName;
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +0000840 if (D->isBitField())
841 ObjCIvarBitfieldGroupOffset(D, IvarOffsetName);
842 else
843 WriteInternalIvarName(ClassDecl, D, IvarOffsetName);
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +0000844
845
846 std::string S = "(*(";
847 QualType IvarT = D->getType();
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +0000848 if (D->isBitField())
849 IvarT = GetGroupRecordTypeForObjCIvarBitfield(D);
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +0000850
851 if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
852 RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
853 RD = RD->getDefinition();
854 if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
855 // decltype(((Foo_IMPL*)0)->bar) *
856 ObjCContainerDecl *CDecl =
857 dyn_cast<ObjCContainerDecl>(D->getDeclContext());
858 // ivar in class extensions requires special treatment.
859 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
860 CDecl = CatDecl->getClassInterface();
861 std::string RecName = CDecl->getName();
862 RecName += "_IMPL";
863 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
864 SourceLocation(), SourceLocation(),
865 &Context->Idents.get(RecName.c_str()));
866 QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
867 unsigned UnsignedIntSize =
868 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
869 Expr *Zero = IntegerLiteral::Create(*Context,
870 llvm::APInt(UnsignedIntSize, 0),
871 Context->UnsignedIntTy, SourceLocation());
872 Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
873 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
874 Zero);
875 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
876 SourceLocation(),
877 &Context->Idents.get(D->getNameAsString()),
878 IvarT, 0,
879 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +0000880 ICIS_NoInit);
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +0000881 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
882 FD->getType(), VK_LValue,
883 OK_Ordinary);
884 IvarT = Context->getDecltypeType(ME, ME->getType());
885 }
886 }
887 convertObjCTypeToCStyleType(IvarT);
888 QualType castT = Context->getPointerType(IvarT);
889 std::string TypeString(castT.getAsString(Context->getPrintingPolicy()));
890 S += TypeString;
891 S += ")";
892
893 // ((char *)self + IVAR_OFFSET_SYMBOL_NAME)
894 S += "((char *)self + ";
895 S += IvarOffsetName;
896 S += "))";
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +0000897 if (D->isBitField()) {
898 S += ".";
899 S += D->getNameAsString();
900 }
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +0000901 ReferencedIvars[const_cast<ObjCInterfaceDecl *>(ClassDecl)].insert(D);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000902 return S;
903}
904
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000905/// mustSynthesizeSetterGetterMethod - returns true if setter or getter has not
906/// been found in the class implementation. In this case, it must be synthesized.
907static bool mustSynthesizeSetterGetterMethod(ObjCImplementationDecl *IMP,
908 ObjCPropertyDecl *PD,
909 bool getter) {
910 return getter ? !IMP->getInstanceMethod(PD->getGetterName())
911 : !IMP->getInstanceMethod(PD->getSetterName());
912
913}
914
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000915void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
916 ObjCImplementationDecl *IMD,
917 ObjCCategoryImplDecl *CID) {
918 static bool objcGetPropertyDefined = false;
919 static bool objcSetPropertyDefined = false;
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000920 SourceLocation startGetterSetterLoc;
921
922 if (PID->getLocStart().isValid()) {
923 SourceLocation startLoc = PID->getLocStart();
924 InsertText(startLoc, "// ");
925 const char *startBuf = SM->getCharacterData(startLoc);
926 assert((*startBuf == '@') && "bogus @synthesize location");
927 const char *semiBuf = strchr(startBuf, ';');
928 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
929 startGetterSetterLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
930 }
931 else
932 startGetterSetterLoc = IMD ? IMD->getLocEnd() : CID->getLocEnd();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000933
934 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
935 return; // FIXME: is this correct?
936
937 // Generate the 'getter' function.
938 ObjCPropertyDecl *PD = PID->getPropertyDecl();
939 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Jordan Rose62bbe072013-03-15 21:41:35 +0000940 assert(IMD && OID && "Synthesized ivars must be attached to @implementation");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000941
Bill Wendlingad017fa2012-12-20 19:22:21 +0000942 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000943 if (mustSynthesizeSetterGetterMethod(IMD, PD, true /*getter*/)) {
Bill Wendlingad017fa2012-12-20 19:22:21 +0000944 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
945 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000946 ObjCPropertyDecl::OBJC_PR_copy));
947 std::string Getr;
948 if (GenGetProperty && !objcGetPropertyDefined) {
949 objcGetPropertyDefined = true;
950 // FIXME. Is this attribute correct in all cases?
951 Getr = "\nextern \"C\" __declspec(dllimport) "
952 "id objc_getProperty(id, SEL, long, bool);\n";
953 }
954 RewriteObjCMethodDecl(OID->getContainingInterface(),
955 PD->getGetterMethodDecl(), Getr);
956 Getr += "{ ";
957 // Synthesize an explicit cast to gain access to the ivar.
958 // See objc-act.c:objc_synthesize_new_getter() for details.
959 if (GenGetProperty) {
960 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
961 Getr += "typedef ";
962 const FunctionType *FPRetType = 0;
963 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
964 FPRetType);
965 Getr += " _TYPE";
966 if (FPRetType) {
967 Getr += ")"; // close the precedence "scope" for "*".
968
969 // Now, emit the argument types (if any).
970 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
971 Getr += "(";
972 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
973 if (i) Getr += ", ";
974 std::string ParamStr = FT->getArgType(i).getAsString(
975 Context->getPrintingPolicy());
976 Getr += ParamStr;
977 }
978 if (FT->isVariadic()) {
979 if (FT->getNumArgs()) Getr += ", ";
980 Getr += "...";
981 }
982 Getr += ")";
983 } else
984 Getr += "()";
985 }
986 Getr += ";\n";
987 Getr += "return (_TYPE)";
988 Getr += "objc_getProperty(self, _cmd, ";
989 RewriteIvarOffsetComputation(OID, Getr);
990 Getr += ", 1)";
991 }
992 else
993 Getr += "return " + getIvarAccessString(OID);
994 Getr += "; }";
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000995 InsertText(startGetterSetterLoc, Getr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000996 }
997
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000998 if (PD->isReadOnly() ||
999 !mustSynthesizeSetterGetterMethod(IMD, PD, false /*setter*/))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001000 return;
1001
1002 // Generate the 'setter' function.
1003 std::string Setr;
Bill Wendlingad017fa2012-12-20 19:22:21 +00001004 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001005 ObjCPropertyDecl::OBJC_PR_copy);
1006 if (GenSetProperty && !objcSetPropertyDefined) {
1007 objcSetPropertyDefined = true;
1008 // FIXME. Is this attribute correct in all cases?
1009 Setr = "\nextern \"C\" __declspec(dllimport) "
1010 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
1011 }
1012
1013 RewriteObjCMethodDecl(OID->getContainingInterface(),
1014 PD->getSetterMethodDecl(), Setr);
1015 Setr += "{ ";
1016 // Synthesize an explicit cast to initialize the ivar.
1017 // See objc-act.c:objc_synthesize_new_setter() for details.
1018 if (GenSetProperty) {
1019 Setr += "objc_setProperty (self, _cmd, ";
1020 RewriteIvarOffsetComputation(OID, Setr);
1021 Setr += ", (id)";
1022 Setr += PD->getName();
1023 Setr += ", ";
Bill Wendlingad017fa2012-12-20 19:22:21 +00001024 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001025 Setr += "0, ";
1026 else
1027 Setr += "1, ";
Bill Wendlingad017fa2012-12-20 19:22:21 +00001028 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001029 Setr += "1)";
1030 else
1031 Setr += "0)";
1032 }
1033 else {
1034 Setr += getIvarAccessString(OID) + " = ";
1035 Setr += PD->getName();
1036 }
Fariborz Jahanian301e2e42012-05-03 22:52:13 +00001037 Setr += "; }\n";
1038 InsertText(startGetterSetterLoc, Setr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001039}
1040
1041static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
1042 std::string &typedefString) {
Fariborz Jahanianbfaa1112013-02-08 17:15:07 +00001043 typedefString += "\n#ifndef _REWRITER_typedef_";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001044 typedefString += ForwardDecl->getNameAsString();
1045 typedefString += "\n";
1046 typedefString += "#define _REWRITER_typedef_";
1047 typedefString += ForwardDecl->getNameAsString();
1048 typedefString += "\n";
1049 typedefString += "typedef struct objc_object ";
1050 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001051 // typedef struct { } _objc_exc_Classname;
1052 typedefString += ";\ntypedef struct {} _objc_exc_";
1053 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001054 typedefString += ";\n#endif\n";
1055}
1056
1057void RewriteModernObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
1058 const std::string &typedefString) {
1059 SourceLocation startLoc = ClassDecl->getLocStart();
1060 const char *startBuf = SM->getCharacterData(startLoc);
1061 const char *semiPtr = strchr(startBuf, ';');
1062 // Replace the @class with typedefs corresponding to the classes.
1063 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
1064}
1065
1066void RewriteModernObjC::RewriteForwardClassDecl(DeclGroupRef D) {
1067 std::string typedefString;
1068 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
Fariborz Jahanian2330df42013-09-24 17:03:07 +00001069 if (ObjCInterfaceDecl *ForwardDecl = dyn_cast<ObjCInterfaceDecl>(*I)) {
1070 if (I == D.begin()) {
1071 // Translate to typedef's that forward reference structs with the same name
1072 // as the class. As a convenience, we include the original declaration
1073 // as a comment.
1074 typedefString += "// @class ";
1075 typedefString += ForwardDecl->getNameAsString();
1076 typedefString += ";";
1077 }
1078 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001079 }
Fariborz Jahanian2330df42013-09-24 17:03:07 +00001080 else
1081 HandleTopLevelSingleDecl(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001082 }
1083 DeclGroupRef::iterator I = D.begin();
1084 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
1085}
1086
1087void RewriteModernObjC::RewriteForwardClassDecl(
Craig Topper6b9240e2013-07-05 19:34:19 +00001088 const SmallVectorImpl<Decl *> &D) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001089 std::string typedefString;
1090 for (unsigned i = 0; i < D.size(); i++) {
1091 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
1092 if (i == 0) {
1093 typedefString += "// @class ";
1094 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanianbfaa1112013-02-08 17:15:07 +00001095 typedefString += ";";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001096 }
1097 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
1098 }
1099 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
1100}
1101
1102void RewriteModernObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
1103 // When method is a synthesized one, such as a getter/setter there is
1104 // nothing to rewrite.
1105 if (Method->isImplicit())
1106 return;
1107 SourceLocation LocStart = Method->getLocStart();
1108 SourceLocation LocEnd = Method->getLocEnd();
1109
1110 if (SM->getExpansionLineNumber(LocEnd) >
1111 SM->getExpansionLineNumber(LocStart)) {
1112 InsertText(LocStart, "#if 0\n");
1113 ReplaceText(LocEnd, 1, ";\n#endif\n");
1114 } else {
1115 InsertText(LocStart, "// ");
1116 }
1117}
1118
1119void RewriteModernObjC::RewriteProperty(ObjCPropertyDecl *prop) {
1120 SourceLocation Loc = prop->getAtLoc();
1121
1122 ReplaceText(Loc, 0, "// ");
1123 // FIXME: handle properties that are declared across multiple lines.
1124}
1125
1126void RewriteModernObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
1127 SourceLocation LocStart = CatDecl->getLocStart();
1128
1129 // FIXME: handle category headers that are declared across multiple lines.
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00001130 if (CatDecl->getIvarRBraceLoc().isValid()) {
1131 ReplaceText(LocStart, 1, "/** ");
1132 ReplaceText(CatDecl->getIvarRBraceLoc(), 1, "**/ ");
1133 }
1134 else {
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001135 ReplaceText(LocStart, 0, "// ");
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00001136 }
Fariborz Jahanianaf300292012-02-20 20:09:20 +00001137
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001138 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
1139 E = CatDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001140 RewriteProperty(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001141
1142 for (ObjCCategoryDecl::instmeth_iterator
1143 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
1144 I != E; ++I)
1145 RewriteMethodDeclaration(*I);
1146 for (ObjCCategoryDecl::classmeth_iterator
1147 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
1148 I != E; ++I)
1149 RewriteMethodDeclaration(*I);
1150
1151 // Lastly, comment out the @end.
1152 ReplaceText(CatDecl->getAtEndRange().getBegin(),
Fariborz Jahanianf9f30792013-04-03 19:11:21 +00001153 strlen("@end"), "/* @end */\n");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001154}
1155
1156void RewriteModernObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
1157 SourceLocation LocStart = PDecl->getLocStart();
1158 assert(PDecl->isThisDeclarationADefinition());
1159
1160 // FIXME: handle protocol headers that are declared across multiple lines.
1161 ReplaceText(LocStart, 0, "// ");
1162
1163 for (ObjCProtocolDecl::instmeth_iterator
1164 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
1165 I != E; ++I)
1166 RewriteMethodDeclaration(*I);
1167 for (ObjCProtocolDecl::classmeth_iterator
1168 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
1169 I != E; ++I)
1170 RewriteMethodDeclaration(*I);
1171
1172 for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
1173 E = PDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001174 RewriteProperty(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001175
1176 // Lastly, comment out the @end.
1177 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Fariborz Jahanianf9f30792013-04-03 19:11:21 +00001178 ReplaceText(LocEnd, strlen("@end"), "/* @end */\n");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001179
1180 // Must comment out @optional/@required
1181 const char *startBuf = SM->getCharacterData(LocStart);
1182 const char *endBuf = SM->getCharacterData(LocEnd);
1183 for (const char *p = startBuf; p < endBuf; p++) {
1184 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
1185 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1186 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
1187
1188 }
1189 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
1190 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1191 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
1192
1193 }
1194 }
1195}
1196
1197void RewriteModernObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1198 SourceLocation LocStart = (*D.begin())->getLocStart();
1199 if (LocStart.isInvalid())
1200 llvm_unreachable("Invalid SourceLocation");
1201 // FIXME: handle forward protocol that are declared across multiple lines.
1202 ReplaceText(LocStart, 0, "// ");
1203}
1204
1205void
Craig Topper6b9240e2013-07-05 19:34:19 +00001206RewriteModernObjC::RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001207 SourceLocation LocStart = DG[0]->getLocStart();
1208 if (LocStart.isInvalid())
1209 llvm_unreachable("Invalid SourceLocation");
1210 // FIXME: handle forward protocol that are declared across multiple lines.
1211 ReplaceText(LocStart, 0, "// ");
1212}
1213
Fariborz Jahanianb3f904f2012-04-03 17:35:38 +00001214void
1215RewriteModernObjC::RewriteLinkageSpec(LinkageSpecDecl *LSD) {
1216 SourceLocation LocStart = LSD->getExternLoc();
1217 if (LocStart.isInvalid())
1218 llvm_unreachable("Invalid extern SourceLocation");
1219
1220 ReplaceText(LocStart, 0, "// ");
1221 if (!LSD->hasBraces())
1222 return;
1223 // FIXME. We don't rewrite well if '{' is not on same line as 'extern'.
1224 SourceLocation LocRBrace = LSD->getRBraceLoc();
1225 if (LocRBrace.isInvalid())
1226 llvm_unreachable("Invalid rbrace SourceLocation");
1227 ReplaceText(LocRBrace, 0, "// ");
1228}
1229
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001230void RewriteModernObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1231 const FunctionType *&FPRetType) {
1232 if (T->isObjCQualifiedIdType())
1233 ResultStr += "id";
1234 else if (T->isFunctionPointerType() ||
1235 T->isBlockPointerType()) {
1236 // needs special handling, since pointer-to-functions have special
1237 // syntax (where a decaration models use).
1238 QualType retType = T;
1239 QualType PointeeTy;
1240 if (const PointerType* PT = retType->getAs<PointerType>())
1241 PointeeTy = PT->getPointeeType();
1242 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
1243 PointeeTy = BPT->getPointeeType();
1244 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
1245 ResultStr += FPRetType->getResultType().getAsString(
1246 Context->getPrintingPolicy());
1247 ResultStr += "(*";
1248 }
1249 } else
1250 ResultStr += T.getAsString(Context->getPrintingPolicy());
1251}
1252
1253void RewriteModernObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1254 ObjCMethodDecl *OMD,
1255 std::string &ResultStr) {
1256 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1257 const FunctionType *FPRetType = 0;
1258 ResultStr += "\nstatic ";
1259 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
1260 ResultStr += " ";
1261
1262 // Unique method name
1263 std::string NameStr;
1264
1265 if (OMD->isInstanceMethod())
1266 NameStr += "_I_";
1267 else
1268 NameStr += "_C_";
1269
1270 NameStr += IDecl->getNameAsString();
1271 NameStr += "_";
1272
1273 if (ObjCCategoryImplDecl *CID =
1274 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
1275 NameStr += CID->getNameAsString();
1276 NameStr += "_";
1277 }
1278 // Append selector names, replacing ':' with '_'
1279 {
1280 std::string selString = OMD->getSelector().getAsString();
1281 int len = selString.size();
1282 for (int i = 0; i < len; i++)
1283 if (selString[i] == ':')
1284 selString[i] = '_';
1285 NameStr += selString;
1286 }
1287 // Remember this name for metadata emission
1288 MethodInternalNames[OMD] = NameStr;
1289 ResultStr += NameStr;
1290
1291 // Rewrite arguments
1292 ResultStr += "(";
1293
1294 // invisible arguments
1295 if (OMD->isInstanceMethod()) {
1296 QualType selfTy = Context->getObjCInterfaceType(IDecl);
1297 selfTy = Context->getPointerType(selfTy);
1298 if (!LangOpts.MicrosoftExt) {
1299 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
1300 ResultStr += "struct ";
1301 }
1302 // When rewriting for Microsoft, explicitly omit the structure name.
1303 ResultStr += IDecl->getNameAsString();
1304 ResultStr += " *";
1305 }
1306 else
1307 ResultStr += Context->getObjCClassType().getAsString(
1308 Context->getPrintingPolicy());
1309
1310 ResultStr += " self, ";
1311 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
1312 ResultStr += " _cmd";
1313
1314 // Method arguments.
1315 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1316 E = OMD->param_end(); PI != E; ++PI) {
1317 ParmVarDecl *PDecl = *PI;
1318 ResultStr += ", ";
1319 if (PDecl->getType()->isObjCQualifiedIdType()) {
1320 ResultStr += "id ";
1321 ResultStr += PDecl->getNameAsString();
1322 } else {
1323 std::string Name = PDecl->getNameAsString();
1324 QualType QT = PDecl->getType();
1325 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian2610f902012-03-27 16:42:20 +00001326 (void)convertBlockPointerToFunctionPointer(QT);
1327 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001328 ResultStr += Name;
1329 }
1330 }
1331 if (OMD->isVariadic())
1332 ResultStr += ", ...";
1333 ResultStr += ") ";
1334
1335 if (FPRetType) {
1336 ResultStr += ")"; // close the precedence "scope" for "*".
1337
1338 // Now, emit the argument types (if any).
1339 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
1340 ResultStr += "(";
1341 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1342 if (i) ResultStr += ", ";
1343 std::string ParamStr = FT->getArgType(i).getAsString(
1344 Context->getPrintingPolicy());
1345 ResultStr += ParamStr;
1346 }
1347 if (FT->isVariadic()) {
1348 if (FT->getNumArgs()) ResultStr += ", ";
1349 ResultStr += "...";
1350 }
1351 ResultStr += ")";
1352 } else {
1353 ResultStr += "()";
1354 }
1355 }
1356}
1357void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) {
1358 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1359 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
1360
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001361 if (IMD) {
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00001362 if (IMD->getIvarRBraceLoc().isValid()) {
1363 ReplaceText(IMD->getLocStart(), 1, "/** ");
1364 ReplaceText(IMD->getIvarRBraceLoc(), 1, "**/ ");
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001365 }
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00001366 else {
1367 InsertText(IMD->getLocStart(), "// ");
1368 }
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001369 }
1370 else
1371 InsertText(CID->getLocStart(), "// ");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001372
1373 for (ObjCCategoryImplDecl::instmeth_iterator
1374 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1375 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
1376 I != E; ++I) {
1377 std::string ResultStr;
1378 ObjCMethodDecl *OMD = *I;
1379 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1380 SourceLocation LocStart = OMD->getLocStart();
1381 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1382
1383 const char *startBuf = SM->getCharacterData(LocStart);
1384 const char *endBuf = SM->getCharacterData(LocEnd);
1385 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1386 }
1387
1388 for (ObjCCategoryImplDecl::classmeth_iterator
1389 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1390 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
1391 I != E; ++I) {
1392 std::string ResultStr;
1393 ObjCMethodDecl *OMD = *I;
1394 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1395 SourceLocation LocStart = OMD->getLocStart();
1396 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1397
1398 const char *startBuf = SM->getCharacterData(LocStart);
1399 const char *endBuf = SM->getCharacterData(LocEnd);
1400 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1401 }
1402 for (ObjCCategoryImplDecl::propimpl_iterator
1403 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
1404 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
1405 I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00001406 RewritePropertyImplDecl(*I, IMD, CID);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001407 }
1408
1409 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
1410}
1411
1412void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00001413 // Do not synthesize more than once.
1414 if (ObjCSynthesizedStructs.count(ClassDecl))
1415 return;
1416 // Make sure super class's are written before current class is written.
1417 ObjCInterfaceDecl *SuperClass = ClassDecl->getSuperClass();
1418 while (SuperClass) {
1419 RewriteInterfaceDecl(SuperClass);
1420 SuperClass = SuperClass->getSuperClass();
1421 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001422 std::string ResultStr;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00001423 if (!ObjCWrittenInterfaces.count(ClassDecl->getCanonicalDecl())) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001424 // we haven't seen a forward decl - generate a typedef.
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001425 RewriteOneForwardClassDecl(ClassDecl, ResultStr);
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00001426 RewriteIvarOffsetSymbols(ClassDecl, ResultStr);
1427
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001428 RewriteObjCInternalStruct(ClassDecl, ResultStr);
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00001429 // Mark this typedef as having been written into its c++ equivalent.
1430 ObjCWrittenInterfaces.insert(ClassDecl->getCanonicalDecl());
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001431
1432 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001433 E = ClassDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001434 RewriteProperty(*I);
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001435 for (ObjCInterfaceDecl::instmeth_iterator
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001436 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001437 I != E; ++I)
1438 RewriteMethodDeclaration(*I);
1439 for (ObjCInterfaceDecl::classmeth_iterator
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001440 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001441 I != E; ++I)
1442 RewriteMethodDeclaration(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001443
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001444 // Lastly, comment out the @end.
1445 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
Fariborz Jahanianf9f30792013-04-03 19:11:21 +00001446 "/* @end */\n");
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001447 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001448}
1449
1450Stmt *RewriteModernObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1451 SourceRange OldRange = PseudoOp->getSourceRange();
1452
1453 // We just magically know some things about the structure of this
1454 // expression.
1455 ObjCMessageExpr *OldMsg =
1456 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1457 PseudoOp->getNumSemanticExprs() - 1));
1458
1459 // Because the rewriter doesn't allow us to rewrite rewritten code,
1460 // we need to suppress rewriting the sub-statements.
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001461 Expr *Base;
1462 SmallVector<Expr*, 2> Args;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001463 {
1464 DisableReplaceStmtScope S(*this);
1465
1466 // Rebuild the base expression if we have one.
1467 Base = 0;
1468 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1469 Base = OldMsg->getInstanceReceiver();
1470 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1471 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1472 }
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001473
1474 unsigned numArgs = OldMsg->getNumArgs();
1475 for (unsigned i = 0; i < numArgs; i++) {
1476 Expr *Arg = OldMsg->getArg(i);
1477 if (isa<OpaqueValueExpr>(Arg))
1478 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1479 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1480 Args.push_back(Arg);
1481 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001482 }
1483
1484 // TODO: avoid this copy.
1485 SmallVector<SourceLocation, 1> SelLocs;
1486 OldMsg->getSelectorLocs(SelLocs);
1487
1488 ObjCMessageExpr *NewMsg = 0;
1489 switch (OldMsg->getReceiverKind()) {
1490 case ObjCMessageExpr::Class:
1491 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1492 OldMsg->getValueKind(),
1493 OldMsg->getLeftLoc(),
1494 OldMsg->getClassReceiverTypeInfo(),
1495 OldMsg->getSelector(),
1496 SelLocs,
1497 OldMsg->getMethodDecl(),
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001498 Args,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001499 OldMsg->getRightLoc(),
1500 OldMsg->isImplicit());
1501 break;
1502
1503 case ObjCMessageExpr::Instance:
1504 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1505 OldMsg->getValueKind(),
1506 OldMsg->getLeftLoc(),
1507 Base,
1508 OldMsg->getSelector(),
1509 SelLocs,
1510 OldMsg->getMethodDecl(),
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001511 Args,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001512 OldMsg->getRightLoc(),
1513 OldMsg->isImplicit());
1514 break;
1515
1516 case ObjCMessageExpr::SuperClass:
1517 case ObjCMessageExpr::SuperInstance:
1518 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1519 OldMsg->getValueKind(),
1520 OldMsg->getLeftLoc(),
1521 OldMsg->getSuperLoc(),
1522 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1523 OldMsg->getSuperType(),
1524 OldMsg->getSelector(),
1525 SelLocs,
1526 OldMsg->getMethodDecl(),
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001527 Args,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001528 OldMsg->getRightLoc(),
1529 OldMsg->isImplicit());
1530 break;
1531 }
1532
1533 Stmt *Replacement = SynthMessageExpr(NewMsg);
1534 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1535 return Replacement;
1536}
1537
1538Stmt *RewriteModernObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1539 SourceRange OldRange = PseudoOp->getSourceRange();
1540
1541 // We just magically know some things about the structure of this
1542 // expression.
1543 ObjCMessageExpr *OldMsg =
1544 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1545
1546 // Because the rewriter doesn't allow us to rewrite rewritten code,
1547 // we need to suppress rewriting the sub-statements.
1548 Expr *Base = 0;
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001549 SmallVector<Expr*, 1> Args;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001550 {
1551 DisableReplaceStmtScope S(*this);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001552 // Rebuild the base expression if we have one.
1553 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1554 Base = OldMsg->getInstanceReceiver();
1555 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1556 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1557 }
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001558 unsigned numArgs = OldMsg->getNumArgs();
1559 for (unsigned i = 0; i < numArgs; i++) {
1560 Expr *Arg = OldMsg->getArg(i);
1561 if (isa<OpaqueValueExpr>(Arg))
1562 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1563 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1564 Args.push_back(Arg);
1565 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001566 }
1567
1568 // Intentionally empty.
1569 SmallVector<SourceLocation, 1> SelLocs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001570
1571 ObjCMessageExpr *NewMsg = 0;
1572 switch (OldMsg->getReceiverKind()) {
1573 case ObjCMessageExpr::Class:
1574 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1575 OldMsg->getValueKind(),
1576 OldMsg->getLeftLoc(),
1577 OldMsg->getClassReceiverTypeInfo(),
1578 OldMsg->getSelector(),
1579 SelLocs,
1580 OldMsg->getMethodDecl(),
1581 Args,
1582 OldMsg->getRightLoc(),
1583 OldMsg->isImplicit());
1584 break;
1585
1586 case ObjCMessageExpr::Instance:
1587 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1588 OldMsg->getValueKind(),
1589 OldMsg->getLeftLoc(),
1590 Base,
1591 OldMsg->getSelector(),
1592 SelLocs,
1593 OldMsg->getMethodDecl(),
1594 Args,
1595 OldMsg->getRightLoc(),
1596 OldMsg->isImplicit());
1597 break;
1598
1599 case ObjCMessageExpr::SuperClass:
1600 case ObjCMessageExpr::SuperInstance:
1601 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1602 OldMsg->getValueKind(),
1603 OldMsg->getLeftLoc(),
1604 OldMsg->getSuperLoc(),
1605 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1606 OldMsg->getSuperType(),
1607 OldMsg->getSelector(),
1608 SelLocs,
1609 OldMsg->getMethodDecl(),
1610 Args,
1611 OldMsg->getRightLoc(),
1612 OldMsg->isImplicit());
1613 break;
1614 }
1615
1616 Stmt *Replacement = SynthMessageExpr(NewMsg);
1617 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1618 return Replacement;
1619}
1620
1621/// SynthCountByEnumWithState - To print:
Fariborz Jahaniane38f08a2013-09-05 17:17:32 +00001622/// ((NSUInteger (*)
1623/// (id, SEL, struct __objcFastEnumerationState *, id *, NSUInteger))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001624/// (void *)objc_msgSend)((id)l_collection,
1625/// sel_registerName(
1626/// "countByEnumeratingWithState:objects:count:"),
1627/// &enumState,
Fariborz Jahaniane38f08a2013-09-05 17:17:32 +00001628/// (id *)__rw_items, (NSUInteger)16)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001629///
1630void RewriteModernObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahaniane38f08a2013-09-05 17:17:32 +00001631 buf += "((_WIN_NSUInteger (*) (id, SEL, struct __objcFastEnumerationState *, "
1632 "id *, _WIN_NSUInteger))(void *)objc_msgSend)";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001633 buf += "\n\t\t";
1634 buf += "((id)l_collection,\n\t\t";
1635 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1636 buf += "\n\t\t";
1637 buf += "&enumState, "
Fariborz Jahaniane38f08a2013-09-05 17:17:32 +00001638 "(id *)__rw_items, (_WIN_NSUInteger)16)";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001639}
1640
1641/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1642/// statement to exit to its outer synthesized loop.
1643///
1644Stmt *RewriteModernObjC::RewriteBreakStmt(BreakStmt *S) {
1645 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1646 return S;
1647 // replace break with goto __break_label
1648 std::string buf;
1649
1650 SourceLocation startLoc = S->getLocStart();
1651 buf = "goto __break_label_";
1652 buf += utostr(ObjCBcLabelNo.back());
1653 ReplaceText(startLoc, strlen("break"), buf);
1654
1655 return 0;
1656}
1657
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00001658void RewriteModernObjC::ConvertSourceLocationToLineDirective(
1659 SourceLocation Loc,
1660 std::string &LineString) {
Fariborz Jahanianada71912013-02-08 00:27:34 +00001661 if (Loc.isFileID() && GenerateLineInfo) {
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00001662 LineString += "\n#line ";
1663 PresumedLoc PLoc = SM->getPresumedLoc(Loc);
1664 LineString += utostr(PLoc.getLine());
1665 LineString += " \"";
1666 LineString += Lexer::Stringify(PLoc.getFilename());
1667 LineString += "\"\n";
1668 }
1669}
1670
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001671/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1672/// statement to continue with its inner synthesized loop.
1673///
1674Stmt *RewriteModernObjC::RewriteContinueStmt(ContinueStmt *S) {
1675 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1676 return S;
1677 // replace continue with goto __continue_label
1678 std::string buf;
1679
1680 SourceLocation startLoc = S->getLocStart();
1681 buf = "goto __continue_label_";
1682 buf += utostr(ObjCBcLabelNo.back());
1683 ReplaceText(startLoc, strlen("continue"), buf);
1684
1685 return 0;
1686}
1687
1688/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
1689/// It rewrites:
1690/// for ( type elem in collection) { stmts; }
1691
1692/// Into:
1693/// {
1694/// type elem;
1695/// struct __objcFastEnumerationState enumState = { 0 };
1696/// id __rw_items[16];
1697/// id l_collection = (id)collection;
Fariborz Jahaniane38f08a2013-09-05 17:17:32 +00001698/// NSUInteger limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001699/// objects:__rw_items count:16];
1700/// if (limit) {
1701/// unsigned long startMutations = *enumState.mutationsPtr;
1702/// do {
1703/// unsigned long counter = 0;
1704/// do {
1705/// if (startMutations != *enumState.mutationsPtr)
1706/// objc_enumerationMutation(l_collection);
1707/// elem = (type)enumState.itemsPtr[counter++];
1708/// stmts;
1709/// __continue_label: ;
1710/// } while (counter < limit);
Fariborz Jahaniane38f08a2013-09-05 17:17:32 +00001711/// } while ((limit = [l_collection countByEnumeratingWithState:&enumState
1712/// objects:__rw_items count:16]));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001713/// elem = nil;
1714/// __break_label: ;
1715/// }
1716/// else
1717/// elem = nil;
1718/// }
1719///
1720Stmt *RewriteModernObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1721 SourceLocation OrigEnd) {
1722 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1723 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1724 "ObjCForCollectionStmt Statement stack mismatch");
1725 assert(!ObjCBcLabelNo.empty() &&
1726 "ObjCForCollectionStmt - Label No stack empty");
1727
1728 SourceLocation startLoc = S->getLocStart();
1729 const char *startBuf = SM->getCharacterData(startLoc);
1730 StringRef elementName;
1731 std::string elementTypeAsString;
1732 std::string buf;
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00001733 // line directive first.
1734 SourceLocation ForEachLoc = S->getForLoc();
1735 ConvertSourceLocationToLineDirective(ForEachLoc, buf);
1736 buf += "{\n\t";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001737 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1738 // type elem;
1739 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1740 QualType ElementType = cast<ValueDecl>(D)->getType();
1741 if (ElementType->isObjCQualifiedIdType() ||
1742 ElementType->isObjCQualifiedInterfaceType())
1743 // Simply use 'id' for all qualified types.
1744 elementTypeAsString = "id";
1745 else
1746 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
1747 buf += elementTypeAsString;
1748 buf += " ";
1749 elementName = D->getName();
1750 buf += elementName;
1751 buf += ";\n\t";
1752 }
1753 else {
1754 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1755 elementName = DR->getDecl()->getName();
1756 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1757 if (VD->getType()->isObjCQualifiedIdType() ||
1758 VD->getType()->isObjCQualifiedInterfaceType())
1759 // Simply use 'id' for all qualified types.
1760 elementTypeAsString = "id";
1761 else
1762 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
1763 }
1764
1765 // struct __objcFastEnumerationState enumState = { 0 };
1766 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1767 // id __rw_items[16];
1768 buf += "id __rw_items[16];\n\t";
1769 // id l_collection = (id)
1770 buf += "id l_collection = (id)";
1771 // Find start location of 'collection' the hard way!
1772 const char *startCollectionBuf = startBuf;
1773 startCollectionBuf += 3; // skip 'for'
1774 startCollectionBuf = strchr(startCollectionBuf, '(');
1775 startCollectionBuf++; // skip '('
1776 // find 'in' and skip it.
1777 while (*startCollectionBuf != ' ' ||
1778 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1779 (*(startCollectionBuf+3) != ' ' &&
1780 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1781 startCollectionBuf++;
1782 startCollectionBuf += 3;
1783
1784 // Replace: "for (type element in" with string constructed thus far.
1785 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1786 // Replace ')' in for '(' type elem in collection ')' with ';'
1787 SourceLocation rightParenLoc = S->getRParenLoc();
1788 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1789 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
1790 buf = ";\n\t";
1791
1792 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1793 // objects:__rw_items count:16];
1794 // which is synthesized into:
Fariborz Jahaniane38f08a2013-09-05 17:17:32 +00001795 // NSUInteger limit =
1796 // ((NSUInteger (*)
1797 // (id, SEL, struct __objcFastEnumerationState *, id *, NSUInteger))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001798 // (void *)objc_msgSend)((id)l_collection,
1799 // sel_registerName(
1800 // "countByEnumeratingWithState:objects:count:"),
1801 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahaniane38f08a2013-09-05 17:17:32 +00001802 // (id *)__rw_items, (NSUInteger)16);
1803 buf += "_WIN_NSUInteger limit =\n\t\t";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001804 SynthCountByEnumWithState(buf);
1805 buf += ";\n\t";
1806 /// if (limit) {
1807 /// unsigned long startMutations = *enumState.mutationsPtr;
1808 /// do {
1809 /// unsigned long counter = 0;
1810 /// do {
1811 /// if (startMutations != *enumState.mutationsPtr)
1812 /// objc_enumerationMutation(l_collection);
1813 /// elem = (type)enumState.itemsPtr[counter++];
1814 buf += "if (limit) {\n\t";
1815 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1816 buf += "do {\n\t\t";
1817 buf += "unsigned long counter = 0;\n\t\t";
1818 buf += "do {\n\t\t\t";
1819 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1820 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1821 buf += elementName;
1822 buf += " = (";
1823 buf += elementTypeAsString;
1824 buf += ")enumState.itemsPtr[counter++];";
1825 // Replace ')' in for '(' type elem in collection ')' with all of these.
1826 ReplaceText(lparenLoc, 1, buf);
1827
1828 /// __continue_label: ;
1829 /// } while (counter < limit);
Fariborz Jahaniane38f08a2013-09-05 17:17:32 +00001830 /// } while ((limit = [l_collection countByEnumeratingWithState:&enumState
1831 /// objects:__rw_items count:16]));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001832 /// elem = nil;
1833 /// __break_label: ;
1834 /// }
1835 /// else
1836 /// elem = nil;
1837 /// }
1838 ///
1839 buf = ";\n\t";
1840 buf += "__continue_label_";
1841 buf += utostr(ObjCBcLabelNo.back());
1842 buf += ": ;";
1843 buf += "\n\t\t";
1844 buf += "} while (counter < limit);\n\t";
Fariborz Jahaniane38f08a2013-09-05 17:17:32 +00001845 buf += "} while ((limit = ";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001846 SynthCountByEnumWithState(buf);
Fariborz Jahaniane38f08a2013-09-05 17:17:32 +00001847 buf += "));\n\t";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001848 buf += elementName;
1849 buf += " = ((";
1850 buf += elementTypeAsString;
1851 buf += ")0);\n\t";
1852 buf += "__break_label_";
1853 buf += utostr(ObjCBcLabelNo.back());
1854 buf += ": ;\n\t";
1855 buf += "}\n\t";
1856 buf += "else\n\t\t";
1857 buf += elementName;
1858 buf += " = ((";
1859 buf += elementTypeAsString;
1860 buf += ")0);\n\t";
1861 buf += "}\n";
1862
1863 // Insert all these *after* the statement body.
1864 // FIXME: If this should support Obj-C++, support CXXTryStmt
1865 if (isa<CompoundStmt>(S->getBody())) {
1866 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
1867 InsertText(endBodyLoc, buf);
1868 } else {
1869 /* Need to treat single statements specially. For example:
1870 *
1871 * for (A *a in b) if (stuff()) break;
1872 * for (A *a in b) xxxyy;
1873 *
1874 * The following code simply scans ahead to the semi to find the actual end.
1875 */
1876 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1877 const char *semiBuf = strchr(stmtBuf, ';');
1878 assert(semiBuf && "Can't find ';'");
1879 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
1880 InsertText(endBodyLoc, buf);
1881 }
1882 Stmts.pop_back();
1883 ObjCBcLabelNo.pop_back();
1884 return 0;
1885}
1886
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001887static void Write_RethrowObject(std::string &buf) {
1888 buf += "{ struct _FIN { _FIN(id reth) : rethrow(reth) {}\n";
1889 buf += "\t~_FIN() { if (rethrow) objc_exception_throw(rethrow); }\n";
1890 buf += "\tid rethrow;\n";
1891 buf += "\t} _fin_force_rethow(_rethrow);";
1892}
1893
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001894/// RewriteObjCSynchronizedStmt -
1895/// This routine rewrites @synchronized(expr) stmt;
1896/// into:
1897/// objc_sync_enter(expr);
1898/// @try stmt @finally { objc_sync_exit(expr); }
1899///
1900Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1901 // Get the start location and compute the semi location.
1902 SourceLocation startLoc = S->getLocStart();
1903 const char *startBuf = SM->getCharacterData(startLoc);
1904
1905 assert((*startBuf == '@') && "bogus @synchronized location");
1906
1907 std::string buf;
Fariborz Jahanian43f4f1e2012-11-07 00:43:05 +00001908 SourceLocation SynchLoc = S->getAtSynchronizedLoc();
1909 ConvertSourceLocationToLineDirective(SynchLoc, buf);
Fariborz Jahanian786e56f2013-09-17 17:51:48 +00001910 buf += "{ id _rethrow = 0; id _sync_obj = (id)";
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001911
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001912 const char *lparenBuf = startBuf;
1913 while (*lparenBuf != '(') lparenBuf++;
1914 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001915
1916 buf = "; objc_sync_enter(_sync_obj);\n";
1917 buf += "try {\n\tstruct _SYNC_EXIT { _SYNC_EXIT(id arg) : sync_exit(arg) {}";
1918 buf += "\n\t~_SYNC_EXIT() {objc_sync_exit(sync_exit);}";
1919 buf += "\n\tid sync_exit;";
1920 buf += "\n\t} _sync_exit(_sync_obj);\n";
1921
1922 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1923 // the sync expression is typically a message expression that's already
1924 // been rewritten! (which implies the SourceLocation's are invalid).
1925 SourceLocation RParenExprLoc = S->getSynchBody()->getLocStart();
1926 const char *RParenExprLocBuf = SM->getCharacterData(RParenExprLoc);
1927 while (*RParenExprLocBuf != ')') RParenExprLocBuf--;
1928 RParenExprLoc = startLoc.getLocWithOffset(RParenExprLocBuf-startBuf);
1929
1930 SourceLocation LBranceLoc = S->getSynchBody()->getLocStart();
1931 const char *LBraceLocBuf = SM->getCharacterData(LBranceLoc);
1932 assert (*LBraceLocBuf == '{');
1933 ReplaceText(RParenExprLoc, (LBraceLocBuf - SM->getCharacterData(RParenExprLoc) + 1), buf);
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001934
Fariborz Jahanianb655bf02012-03-16 21:43:45 +00001935 SourceLocation startRBraceLoc = S->getSynchBody()->getLocEnd();
Matt Beaumont-Gay9ab511c2012-03-16 22:20:39 +00001936 assert((*SM->getCharacterData(startRBraceLoc) == '}') &&
1937 "bogus @synchronized block");
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001938
1939 buf = "} catch (id e) {_rethrow = e;}\n";
1940 Write_RethrowObject(buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001941 buf += "}\n";
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001942 buf += "}\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001943
Fariborz Jahanianb655bf02012-03-16 21:43:45 +00001944 ReplaceText(startRBraceLoc, 1, buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001945
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001946 return 0;
1947}
1948
1949void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S)
1950{
1951 // Perform a bottom up traversal of all children.
1952 for (Stmt::child_range CI = S->children(); CI; ++CI)
1953 if (*CI)
1954 WarnAboutReturnGotoStmts(*CI);
1955
1956 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
1957 Diags.Report(Context->getFullLoc(S->getLocStart()),
1958 TryFinallyContainsReturnDiag);
1959 }
1960 return;
1961}
1962
Fariborz Jahanian042b91d2012-05-23 23:47:20 +00001963Stmt *RewriteModernObjC::RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) {
1964 SourceLocation startLoc = S->getAtLoc();
1965 ReplaceText(startLoc, strlen("@autoreleasepool"), "/* @autoreleasepool */");
Fariborz Jahanianc9b72b62012-05-24 22:59:56 +00001966 ReplaceText(S->getSubStmt()->getLocStart(), 1,
1967 "{ __AtAutoreleasePool __autoreleasepool; ");
Fariborz Jahanian042b91d2012-05-23 23:47:20 +00001968
1969 return 0;
1970}
1971
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001972Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001973 ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt();
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001974 bool noCatch = S->getNumCatchStmts() == 0;
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001975 std::string buf;
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00001976 SourceLocation TryLocation = S->getAtTryLoc();
1977 ConvertSourceLocationToLineDirective(TryLocation, buf);
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001978
1979 if (finalStmt) {
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001980 if (noCatch)
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00001981 buf += "{ id volatile _rethrow = 0;\n";
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001982 else {
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00001983 buf += "{ id volatile _rethrow = 0;\ntry {\n";
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001984 }
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001985 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001986 // Get the start location and compute the semi location.
1987 SourceLocation startLoc = S->getLocStart();
1988 const char *startBuf = SM->getCharacterData(startLoc);
1989
1990 assert((*startBuf == '@') && "bogus @try location");
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001991 if (finalStmt)
1992 ReplaceText(startLoc, 1, buf);
1993 else
1994 // @try -> try
1995 ReplaceText(startLoc, 1, "");
1996
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001997 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1998 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Fariborz Jahanian4c148812012-03-15 20:11:10 +00001999 VarDecl *catchDecl = Catch->getCatchParamDecl();
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00002000
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002001 startLoc = Catch->getLocStart();
Fariborz Jahanian4c148812012-03-15 20:11:10 +00002002 bool AtRemoved = false;
2003 if (catchDecl) {
2004 QualType t = catchDecl->getType();
2005 if (const ObjCObjectPointerType *Ptr = t->getAs<ObjCObjectPointerType>()) {
2006 // Should be a pointer to a class.
2007 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
2008 if (IDecl) {
2009 std::string Result;
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00002010 ConvertSourceLocationToLineDirective(Catch->getLocStart(), Result);
2011
Fariborz Jahanian4c148812012-03-15 20:11:10 +00002012 startBuf = SM->getCharacterData(startLoc);
2013 assert((*startBuf == '@') && "bogus @catch location");
2014 SourceLocation rParenLoc = Catch->getRParenLoc();
2015 const char *rParenBuf = SM->getCharacterData(rParenLoc);
2016
2017 // _objc_exc_Foo *_e as argument to catch.
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00002018 Result += "catch (_objc_exc_"; Result += IDecl->getNameAsString();
Fariborz Jahanian4c148812012-03-15 20:11:10 +00002019 Result += " *_"; Result += catchDecl->getNameAsString();
2020 Result += ")";
2021 ReplaceText(startLoc, rParenBuf-startBuf+1, Result);
2022 // Foo *e = (Foo *)_e;
2023 Result.clear();
2024 Result = "{ ";
2025 Result += IDecl->getNameAsString();
2026 Result += " *"; Result += catchDecl->getNameAsString();
2027 Result += " = ("; Result += IDecl->getNameAsString(); Result += "*)";
2028 Result += "_"; Result += catchDecl->getNameAsString();
2029
2030 Result += "; ";
2031 SourceLocation lBraceLoc = Catch->getCatchBody()->getLocStart();
2032 ReplaceText(lBraceLoc, 1, Result);
2033 AtRemoved = true;
2034 }
2035 }
2036 }
2037 if (!AtRemoved)
2038 // @catch -> catch
2039 ReplaceText(startLoc, 1, "");
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00002040
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002041 }
Fariborz Jahanian220419a2012-03-15 23:50:33 +00002042 if (finalStmt) {
2043 buf.clear();
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00002044 SourceLocation FinallyLoc = finalStmt->getLocStart();
2045
2046 if (noCatch) {
2047 ConvertSourceLocationToLineDirective(FinallyLoc, buf);
2048 buf += "catch (id e) {_rethrow = e;}\n";
2049 }
2050 else {
2051 buf += "}\n";
2052 ConvertSourceLocationToLineDirective(FinallyLoc, buf);
2053 buf += "catch (id e) {_rethrow = e;}\n";
2054 }
2055
Fariborz Jahanian220419a2012-03-15 23:50:33 +00002056 SourceLocation startFinalLoc = finalStmt->getLocStart();
2057 ReplaceText(startFinalLoc, 8, buf);
2058 Stmt *body = finalStmt->getFinallyBody();
2059 SourceLocation startFinalBodyLoc = body->getLocStart();
2060 buf.clear();
Fariborz Jahanian542125f2012-03-16 21:33:16 +00002061 Write_RethrowObject(buf);
Fariborz Jahanian220419a2012-03-15 23:50:33 +00002062 ReplaceText(startFinalBodyLoc, 1, buf);
2063
2064 SourceLocation endFinalBodyLoc = body->getLocEnd();
2065 ReplaceText(endFinalBodyLoc, 1, "}\n}");
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00002066 // Now check for any return/continue/go statements within the @try.
2067 WarnAboutReturnGotoStmts(S->getTryBody());
Fariborz Jahanian220419a2012-03-15 23:50:33 +00002068 }
2069
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002070 return 0;
2071}
2072
2073// This can't be done with ReplaceStmt(S, ThrowExpr), since
2074// the throw expression is typically a message expression that's already
2075// been rewritten! (which implies the SourceLocation's are invalid).
2076Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
2077 // Get the start location and compute the semi location.
2078 SourceLocation startLoc = S->getLocStart();
2079 const char *startBuf = SM->getCharacterData(startLoc);
2080
2081 assert((*startBuf == '@') && "bogus @throw location");
2082
2083 std::string buf;
2084 /* void objc_exception_throw(id) __attribute__((noreturn)); */
2085 if (S->getThrowExpr())
2086 buf = "objc_exception_throw(";
Fariborz Jahanian40539462012-03-16 16:52:06 +00002087 else
2088 buf = "throw";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002089
2090 // handle "@ throw" correctly.
2091 const char *wBuf = strchr(startBuf, 'w');
2092 assert((*wBuf == 'w') && "@throw: can't find 'w'");
2093 ReplaceText(startLoc, wBuf-startBuf+1, buf);
2094
Fariborz Jahaniana09cd812013-02-11 19:30:33 +00002095 SourceLocation endLoc = S->getLocEnd();
2096 const char *endBuf = SM->getCharacterData(endLoc);
2097 const char *semiBuf = strchr(endBuf, ';');
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002098 assert((*semiBuf == ';') && "@throw: can't find ';'");
2099 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Fariborz Jahanian40539462012-03-16 16:52:06 +00002100 if (S->getThrowExpr())
2101 ReplaceText(semiLoc, 1, ");");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002102 return 0;
2103}
2104
2105Stmt *RewriteModernObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
2106 // Create a new string expression.
2107 QualType StrType = Context->getPointerType(Context->CharTy);
2108 std::string StrEncoding;
2109 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
2110 Expr *Replacement = StringLiteral::Create(*Context, StrEncoding,
2111 StringLiteral::Ascii, false,
2112 StrType, SourceLocation());
2113 ReplaceStmt(Exp, Replacement);
2114
2115 // Replace this subexpr in the parent.
2116 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2117 return Replacement;
2118}
2119
2120Stmt *RewriteModernObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
2121 if (!SelGetUidFunctionDecl)
2122 SynthSelGetUidFunctionDecl();
2123 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2124 // Create a call to sel_registerName("selName").
2125 SmallVector<Expr*, 8> SelExprs;
2126 QualType argType = Context->getPointerType(Context->CharTy);
2127 SelExprs.push_back(StringLiteral::Create(*Context,
2128 Exp->getSelector().getAsString(),
2129 StringLiteral::Ascii, false,
2130 argType, SourceLocation()));
2131 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2132 &SelExprs[0], SelExprs.size());
2133 ReplaceStmt(Exp, SelExp);
2134 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2135 return SelExp;
2136}
2137
2138CallExpr *RewriteModernObjC::SynthesizeCallToFunctionDecl(
2139 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2140 SourceLocation EndLoc) {
2141 // Get the type, we will need to reference it in a couple spots.
2142 QualType msgSendType = FD->getType();
2143
2144 // Create a reference to the objc_msgSend() declaration.
2145 DeclRefExpr *DRE =
John McCallf4b88a42012-03-10 09:33:50 +00002146 new (Context) DeclRefExpr(FD, false, msgSendType, VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002147
2148 // Now, we cast the reference to a pointer to the objc_msgSend type.
2149 QualType pToFunc = Context->getPointerType(msgSendType);
2150 ImplicitCastExpr *ICE =
2151 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
2152 DRE, 0, VK_RValue);
2153
2154 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2155
2156 CallExpr *Exp =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002157 new (Context) CallExpr(*Context, ICE, llvm::makeArrayRef(args, nargs),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002158 FT->getCallResultType(*Context),
2159 VK_RValue, EndLoc);
2160 return Exp;
2161}
2162
2163static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2164 const char *&startRef, const char *&endRef) {
2165 while (startBuf < endBuf) {
2166 if (*startBuf == '<')
2167 startRef = startBuf; // mark the start.
2168 if (*startBuf == '>') {
2169 if (startRef && *startRef == '<') {
2170 endRef = startBuf; // mark the end.
2171 return true;
2172 }
2173 return false;
2174 }
2175 startBuf++;
2176 }
2177 return false;
2178}
2179
2180static void scanToNextArgument(const char *&argRef) {
2181 int angle = 0;
2182 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2183 if (*argRef == '<')
2184 angle++;
2185 else if (*argRef == '>')
2186 angle--;
2187 argRef++;
2188 }
2189 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2190}
2191
2192bool RewriteModernObjC::needToScanForQualifiers(QualType T) {
2193 if (T->isObjCQualifiedIdType())
2194 return true;
2195 if (const PointerType *PT = T->getAs<PointerType>()) {
2196 if (PT->getPointeeType()->isObjCQualifiedIdType())
2197 return true;
2198 }
2199 if (T->isObjCObjectPointerType()) {
2200 T = T->getPointeeType();
2201 return T->isObjCQualifiedInterfaceType();
2202 }
2203 if (T->isArrayType()) {
2204 QualType ElemTy = Context->getBaseElementType(T);
2205 return needToScanForQualifiers(ElemTy);
2206 }
2207 return false;
2208}
2209
2210void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2211 QualType Type = E->getType();
2212 if (needToScanForQualifiers(Type)) {
2213 SourceLocation Loc, EndLoc;
2214
2215 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2216 Loc = ECE->getLParenLoc();
2217 EndLoc = ECE->getRParenLoc();
2218 } else {
2219 Loc = E->getLocStart();
2220 EndLoc = E->getLocEnd();
2221 }
2222 // This will defend against trying to rewrite synthesized expressions.
2223 if (Loc.isInvalid() || EndLoc.isInvalid())
2224 return;
2225
2226 const char *startBuf = SM->getCharacterData(Loc);
2227 const char *endBuf = SM->getCharacterData(EndLoc);
2228 const char *startRef = 0, *endRef = 0;
2229 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2230 // Get the locations of the startRef, endRef.
2231 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2232 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2233 // Comment out the protocol references.
2234 InsertText(LessLoc, "/*");
2235 InsertText(GreaterLoc, "*/");
2236 }
2237 }
2238}
2239
2240void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2241 SourceLocation Loc;
2242 QualType Type;
2243 const FunctionProtoType *proto = 0;
2244 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2245 Loc = VD->getLocation();
2246 Type = VD->getType();
2247 }
2248 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2249 Loc = FD->getLocation();
2250 // Check for ObjC 'id' and class types that have been adorned with protocol
2251 // information (id<p>, C<p>*). The protocol references need to be rewritten!
2252 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2253 assert(funcType && "missing function type");
2254 proto = dyn_cast<FunctionProtoType>(funcType);
2255 if (!proto)
2256 return;
2257 Type = proto->getResultType();
2258 }
2259 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2260 Loc = FD->getLocation();
2261 Type = FD->getType();
2262 }
Fariborz Jahanianf9f30792013-04-03 19:11:21 +00002263 else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(Dcl)) {
2264 Loc = TD->getLocation();
2265 Type = TD->getUnderlyingType();
2266 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002267 else
2268 return;
2269
2270 if (needToScanForQualifiers(Type)) {
2271 // Since types are unique, we need to scan the buffer.
2272
2273 const char *endBuf = SM->getCharacterData(Loc);
2274 const char *startBuf = endBuf;
2275 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
2276 startBuf--; // scan backward (from the decl location) for return type.
2277 const char *startRef = 0, *endRef = 0;
2278 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2279 // Get the locations of the startRef, endRef.
2280 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2281 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2282 // Comment out the protocol references.
2283 InsertText(LessLoc, "/*");
2284 InsertText(GreaterLoc, "*/");
2285 }
2286 }
2287 if (!proto)
2288 return; // most likely, was a variable
2289 // Now check arguments.
2290 const char *startBuf = SM->getCharacterData(Loc);
2291 const char *startFuncBuf = startBuf;
2292 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2293 if (needToScanForQualifiers(proto->getArgType(i))) {
2294 // Since types are unique, we need to scan the buffer.
2295
2296 const char *endBuf = startBuf;
2297 // scan forward (from the decl location) for argument types.
2298 scanToNextArgument(endBuf);
2299 const char *startRef = 0, *endRef = 0;
2300 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2301 // Get the locations of the startRef, endRef.
2302 SourceLocation LessLoc =
2303 Loc.getLocWithOffset(startRef-startFuncBuf);
2304 SourceLocation GreaterLoc =
2305 Loc.getLocWithOffset(endRef-startFuncBuf+1);
2306 // Comment out the protocol references.
2307 InsertText(LessLoc, "/*");
2308 InsertText(GreaterLoc, "*/");
2309 }
2310 startBuf = ++endBuf;
2311 }
2312 else {
2313 // If the function name is derived from a macro expansion, then the
2314 // argument buffer will not follow the name. Need to speak with Chris.
2315 while (*startBuf && *startBuf != ')' && *startBuf != ',')
2316 startBuf++; // scan forward (from the decl location) for argument types.
2317 startBuf++;
2318 }
2319 }
2320}
2321
2322void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) {
2323 QualType QT = ND->getType();
2324 const Type* TypePtr = QT->getAs<Type>();
2325 if (!isa<TypeOfExprType>(TypePtr))
2326 return;
2327 while (isa<TypeOfExprType>(TypePtr)) {
2328 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2329 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2330 TypePtr = QT->getAs<Type>();
2331 }
2332 // FIXME. This will not work for multiple declarators; as in:
2333 // __typeof__(a) b,c,d;
2334 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2335 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2336 const char *startBuf = SM->getCharacterData(DeclLoc);
2337 if (ND->getInit()) {
2338 std::string Name(ND->getNameAsString());
2339 TypeAsString += " " + Name + " = ";
2340 Expr *E = ND->getInit();
2341 SourceLocation startLoc;
2342 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2343 startLoc = ECE->getLParenLoc();
2344 else
2345 startLoc = E->getLocStart();
2346 startLoc = SM->getExpansionLoc(startLoc);
2347 const char *endBuf = SM->getCharacterData(startLoc);
2348 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2349 }
2350 else {
2351 SourceLocation X = ND->getLocEnd();
2352 X = SM->getExpansionLoc(X);
2353 const char *endBuf = SM->getCharacterData(X);
2354 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2355 }
2356}
2357
2358// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2359void RewriteModernObjC::SynthSelGetUidFunctionDecl() {
2360 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2361 SmallVector<QualType, 16> ArgTys;
2362 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2363 QualType getFuncType =
Jordan Rosebea522f2013-03-08 21:51:21 +00002364 getSimpleFunctionType(Context->getObjCSelType(), ArgTys);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002365 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002366 SourceLocation(),
2367 SourceLocation(),
2368 SelGetUidIdent, getFuncType, 0,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002369 SC_Extern);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002370}
2371
2372void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2373 // declared in <objc/objc.h>
2374 if (FD->getIdentifier() &&
2375 FD->getName() == "sel_registerName") {
2376 SelGetUidFunctionDecl = FD;
2377 return;
2378 }
2379 RewriteObjCQualifiedInterfaceTypes(FD);
2380}
2381
2382void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2383 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2384 const char *argPtr = TypeString.c_str();
2385 if (!strchr(argPtr, '^')) {
2386 Str += TypeString;
2387 return;
2388 }
2389 while (*argPtr) {
2390 Str += (*argPtr == '^' ? '*' : *argPtr);
2391 argPtr++;
2392 }
2393}
2394
2395// FIXME. Consolidate this routine with RewriteBlockPointerType.
2396void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2397 ValueDecl *VD) {
2398 QualType Type = VD->getType();
2399 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2400 const char *argPtr = TypeString.c_str();
2401 int paren = 0;
2402 while (*argPtr) {
2403 switch (*argPtr) {
2404 case '(':
2405 Str += *argPtr;
2406 paren++;
2407 break;
2408 case ')':
2409 Str += *argPtr;
2410 paren--;
2411 break;
2412 case '^':
2413 Str += '*';
2414 if (paren == 1)
2415 Str += VD->getNameAsString();
2416 break;
2417 default:
2418 Str += *argPtr;
2419 break;
2420 }
2421 argPtr++;
2422 }
2423}
2424
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00002425void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2426 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2427 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2428 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2429 if (!proto)
2430 return;
2431 QualType Type = proto->getResultType();
2432 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2433 FdStr += " ";
2434 FdStr += FD->getName();
2435 FdStr += "(";
2436 unsigned numArgs = proto->getNumArgs();
2437 for (unsigned i = 0; i < numArgs; i++) {
2438 QualType ArgType = proto->getArgType(i);
2439 RewriteBlockPointerType(FdStr, ArgType);
2440 if (i+1 < numArgs)
2441 FdStr += ", ";
2442 }
Fariborz Jahanianb5863da2012-04-19 16:30:28 +00002443 if (FD->isVariadic()) {
2444 FdStr += (numArgs > 0) ? ", ...);\n" : "...);\n";
2445 }
2446 else
2447 FdStr += ");\n";
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00002448 InsertText(FunLocStart, FdStr);
2449}
2450
Benjamin Kramere5753592013-09-09 14:48:42 +00002451// SynthSuperConstructorFunctionDecl - id __rw_objc_super(id obj, id super);
2452void RewriteModernObjC::SynthSuperConstructorFunctionDecl() {
2453 if (SuperConstructorFunctionDecl)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002454 return;
2455 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2456 SmallVector<QualType, 16> ArgTys;
2457 QualType argT = Context->getObjCIdType();
2458 assert(!argT.isNull() && "Can't find 'id' type");
2459 ArgTys.push_back(argT);
2460 ArgTys.push_back(argT);
2461 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rosebea522f2013-03-08 21:51:21 +00002462 ArgTys);
Benjamin Kramere5753592013-09-09 14:48:42 +00002463 SuperConstructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002464 SourceLocation(),
2465 SourceLocation(),
2466 msgSendIdent, msgSendType,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002467 0, SC_Extern);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002468}
2469
2470// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2471void RewriteModernObjC::SynthMsgSendFunctionDecl() {
2472 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2473 SmallVector<QualType, 16> ArgTys;
2474 QualType argT = Context->getObjCIdType();
2475 assert(!argT.isNull() && "Can't find 'id' type");
2476 ArgTys.push_back(argT);
2477 argT = Context->getObjCSelType();
2478 assert(!argT.isNull() && "Can't find 'SEL' type");
2479 ArgTys.push_back(argT);
2480 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rosebea522f2013-03-08 21:51:21 +00002481 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002482 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002483 SourceLocation(),
2484 SourceLocation(),
2485 msgSendIdent, msgSendType, 0,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002486 SC_Extern);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002487}
2488
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002489// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(void);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002490void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() {
2491 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002492 SmallVector<QualType, 2> ArgTys;
2493 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002494 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rosebea522f2013-03-08 21:51:21 +00002495 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002496 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002497 SourceLocation(),
2498 SourceLocation(),
2499 msgSendIdent, msgSendType, 0,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002500 SC_Extern);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002501}
2502
2503// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2504void RewriteModernObjC::SynthMsgSendStretFunctionDecl() {
2505 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2506 SmallVector<QualType, 16> ArgTys;
2507 QualType argT = Context->getObjCIdType();
2508 assert(!argT.isNull() && "Can't find 'id' type");
2509 ArgTys.push_back(argT);
2510 argT = Context->getObjCSelType();
2511 assert(!argT.isNull() && "Can't find 'SEL' type");
2512 ArgTys.push_back(argT);
2513 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rosebea522f2013-03-08 21:51:21 +00002514 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002515 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002516 SourceLocation(),
2517 SourceLocation(),
2518 msgSendIdent, msgSendType, 0,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002519 SC_Extern);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002520}
2521
2522// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002523// id objc_msgSendSuper_stret(void);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002524void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() {
2525 IdentifierInfo *msgSendIdent =
2526 &Context->Idents.get("objc_msgSendSuper_stret");
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002527 SmallVector<QualType, 2> ArgTys;
2528 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002529 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rosebea522f2013-03-08 21:51:21 +00002530 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002531 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2532 SourceLocation(),
2533 SourceLocation(),
Chad Rosiere3b29882013-01-04 22:40:33 +00002534 msgSendIdent,
2535 msgSendType, 0,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002536 SC_Extern);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002537}
2538
2539// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2540void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() {
2541 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2542 SmallVector<QualType, 16> ArgTys;
2543 QualType argT = Context->getObjCIdType();
2544 assert(!argT.isNull() && "Can't find 'id' type");
2545 ArgTys.push_back(argT);
2546 argT = Context->getObjCSelType();
2547 assert(!argT.isNull() && "Can't find 'SEL' type");
2548 ArgTys.push_back(argT);
2549 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
Jordan Rosebea522f2013-03-08 21:51:21 +00002550 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002551 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002552 SourceLocation(),
2553 SourceLocation(),
2554 msgSendIdent, msgSendType, 0,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002555 SC_Extern);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002556}
2557
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00002558// SynthGetClassFunctionDecl - Class objc_getClass(const char *name);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002559void RewriteModernObjC::SynthGetClassFunctionDecl() {
2560 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2561 SmallVector<QualType, 16> ArgTys;
2562 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00002563 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Jordan Rosebea522f2013-03-08 21:51:21 +00002564 ArgTys);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002565 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002566 SourceLocation(),
2567 SourceLocation(),
2568 getClassIdent, getClassType, 0,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002569 SC_Extern);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002570}
2571
2572// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2573void RewriteModernObjC::SynthGetSuperClassFunctionDecl() {
2574 IdentifierInfo *getSuperClassIdent =
2575 &Context->Idents.get("class_getSuperclass");
2576 SmallVector<QualType, 16> ArgTys;
2577 ArgTys.push_back(Context->getObjCClassType());
2578 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Jordan Rosebea522f2013-03-08 21:51:21 +00002579 ArgTys);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002580 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2581 SourceLocation(),
2582 SourceLocation(),
2583 getSuperClassIdent,
2584 getClassType, 0,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002585 SC_Extern);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002586}
2587
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00002588// SynthGetMetaClassFunctionDecl - Class objc_getMetaClass(const char *name);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002589void RewriteModernObjC::SynthGetMetaClassFunctionDecl() {
2590 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2591 SmallVector<QualType, 16> ArgTys;
2592 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00002593 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Jordan Rosebea522f2013-03-08 21:51:21 +00002594 ArgTys);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002595 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002596 SourceLocation(),
2597 SourceLocation(),
2598 getClassIdent, getClassType,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002599 0, SC_Extern);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002600}
2601
2602Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
2603 QualType strType = getConstantStringStructType();
2604
2605 std::string S = "__NSConstantStringImpl_";
2606
2607 std::string tmpName = InFileName;
2608 unsigned i;
2609 for (i=0; i < tmpName.length(); i++) {
2610 char c = tmpName.at(i);
2611 // replace any non alphanumeric characters with '_'.
Jordan Rose3f6f51e2013-02-08 22:30:41 +00002612 if (!isAlphanumeric(c))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002613 tmpName[i] = '_';
2614 }
2615 S += tmpName;
2616 S += "_";
2617 S += utostr(NumObjCStringLiterals++);
2618
2619 Preamble += "static __NSConstantStringImpl " + S;
2620 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2621 Preamble += "0x000007c8,"; // utf8_str
2622 // The pretty printer for StringLiteral handles escape characters properly.
2623 std::string prettyBufS;
2624 llvm::raw_string_ostream prettyBuf(prettyBufS);
Richard Smithd1420c62012-08-16 03:56:14 +00002625 Exp->getString()->printPretty(prettyBuf, 0, PrintingPolicy(LangOpts));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002626 Preamble += prettyBuf.str();
2627 Preamble += ",";
2628 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2629
2630 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2631 SourceLocation(), &Context->Idents.get(S),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002632 strType, 0, SC_Static);
John McCallf4b88a42012-03-10 09:33:50 +00002633 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002634 SourceLocation());
2635 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
2636 Context->getPointerType(DRE->getType()),
2637 VK_RValue, OK_Ordinary,
2638 SourceLocation());
2639 // cast to NSConstantString *
2640 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2641 CK_CPointerToObjCPointerCast, Unop);
2642 ReplaceStmt(Exp, cast);
2643 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2644 return cast;
2645}
2646
Fariborz Jahanian55947042012-03-27 20:17:30 +00002647Stmt *RewriteModernObjC::RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp) {
2648 unsigned IntSize =
2649 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
2650
2651 Expr *FlagExp = IntegerLiteral::Create(*Context,
2652 llvm::APInt(IntSize, Exp->getValue()),
2653 Context->IntTy, Exp->getLocation());
2654 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Context->ObjCBuiltinBoolTy,
2655 CK_BitCast, FlagExp);
2656 ParenExpr *PE = new (Context) ParenExpr(Exp->getLocation(), Exp->getExprLoc(),
2657 cast);
2658 ReplaceStmt(Exp, PE);
2659 return PE;
2660}
2661
Patrick Beardeb382ec2012-04-19 00:25:12 +00002662Stmt *RewriteModernObjC::RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp) {
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002663 // synthesize declaration of helper functions needed in this routine.
2664 if (!SelGetUidFunctionDecl)
2665 SynthSelGetUidFunctionDecl();
2666 // use objc_msgSend() for all.
2667 if (!MsgSendFunctionDecl)
2668 SynthMsgSendFunctionDecl();
2669 if (!GetClassFunctionDecl)
2670 SynthGetClassFunctionDecl();
2671
2672 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2673 SourceLocation StartLoc = Exp->getLocStart();
2674 SourceLocation EndLoc = Exp->getLocEnd();
2675
2676 // Synthesize a call to objc_msgSend().
2677 SmallVector<Expr*, 4> MsgExprs;
2678 SmallVector<Expr*, 4> ClsExprs;
2679 QualType argType = Context->getPointerType(Context->CharTy);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002680
Patrick Beardeb382ec2012-04-19 00:25:12 +00002681 // Create a call to objc_getClass("<BoxingClass>"). It will be the 1st argument.
2682 ObjCMethodDecl *BoxingMethod = Exp->getBoxingMethod();
2683 ObjCInterfaceDecl *BoxingClass = BoxingMethod->getClassInterface();
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002684
Patrick Beardeb382ec2012-04-19 00:25:12 +00002685 IdentifierInfo *clsName = BoxingClass->getIdentifier();
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002686 ClsExprs.push_back(StringLiteral::Create(*Context,
2687 clsName->getName(),
2688 StringLiteral::Ascii, false,
2689 argType, SourceLocation()));
2690 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2691 &ClsExprs[0],
2692 ClsExprs.size(),
2693 StartLoc, EndLoc);
2694 MsgExprs.push_back(Cls);
2695
Patrick Beardeb382ec2012-04-19 00:25:12 +00002696 // Create a call to sel_registerName("<BoxingMethod>:"), etc.
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002697 // it will be the 2nd argument.
2698 SmallVector<Expr*, 4> SelExprs;
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002699 SelExprs.push_back(StringLiteral::Create(*Context,
Patrick Beardeb382ec2012-04-19 00:25:12 +00002700 BoxingMethod->getSelector().getAsString(),
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002701 StringLiteral::Ascii, false,
2702 argType, SourceLocation()));
2703 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2704 &SelExprs[0], SelExprs.size(),
2705 StartLoc, EndLoc);
2706 MsgExprs.push_back(SelExp);
2707
Patrick Beardeb382ec2012-04-19 00:25:12 +00002708 // User provided sub-expression is the 3rd, and last, argument.
2709 Expr *subExpr = Exp->getSubExpr();
2710 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(subExpr)) {
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002711 QualType type = ICE->getType();
2712 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2713 CastKind CK = CK_BitCast;
2714 if (SubExpr->getType()->isIntegralType(*Context) && type->isBooleanType())
2715 CK = CK_IntegralToBoolean;
Patrick Beardeb382ec2012-04-19 00:25:12 +00002716 subExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, subExpr);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002717 }
Patrick Beardeb382ec2012-04-19 00:25:12 +00002718 MsgExprs.push_back(subExpr);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002719
2720 SmallVector<QualType, 4> ArgTypes;
2721 ArgTypes.push_back(Context->getObjCIdType());
2722 ArgTypes.push_back(Context->getObjCSelType());
Patrick Beardeb382ec2012-04-19 00:25:12 +00002723 for (ObjCMethodDecl::param_iterator PI = BoxingMethod->param_begin(),
2724 E = BoxingMethod->param_end(); PI != E; ++PI)
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002725 ArgTypes.push_back((*PI)->getType());
Patrick Beardeb382ec2012-04-19 00:25:12 +00002726
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002727 QualType returnType = Exp->getType();
2728 // Get the type, we will need to reference it in a couple spots.
2729 QualType msgSendType = MsgSendFlavor->getType();
2730
2731 // Create a reference to the objc_msgSend() declaration.
2732 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2733 VK_LValue, SourceLocation());
2734
2735 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
Patrick Beardeb382ec2012-04-19 00:25:12 +00002736 Context->getPointerType(Context->VoidTy),
2737 CK_BitCast, DRE);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002738
2739 // Now do the "normal" pointer to function cast.
2740 QualType castType =
Jordan Rosebea522f2013-03-08 21:51:21 +00002741 getSimpleFunctionType(returnType, ArgTypes, BoxingMethod->isVariadic());
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002742 castType = Context->getPointerType(castType);
2743 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2744 cast);
2745
2746 // Don't forget the parens to enforce the proper binding.
2747 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2748
2749 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002750 CallExpr *CE = new (Context) CallExpr(*Context, PE, MsgExprs,
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002751 FT->getResultType(), VK_RValue,
2752 EndLoc);
2753 ReplaceStmt(Exp, CE);
2754 return CE;
2755}
2756
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002757Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) {
2758 // synthesize declaration of helper functions needed in this routine.
2759 if (!SelGetUidFunctionDecl)
2760 SynthSelGetUidFunctionDecl();
2761 // use objc_msgSend() for all.
2762 if (!MsgSendFunctionDecl)
2763 SynthMsgSendFunctionDecl();
2764 if (!GetClassFunctionDecl)
2765 SynthGetClassFunctionDecl();
2766
2767 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2768 SourceLocation StartLoc = Exp->getLocStart();
2769 SourceLocation EndLoc = Exp->getLocEnd();
2770
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002771 // Build the expression: __NSContainer_literal(int, ...).arr
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002772 QualType IntQT = Context->IntTy;
2773 QualType NSArrayFType =
Jordan Rosebea522f2013-03-08 21:51:21 +00002774 getSimpleFunctionType(Context->VoidTy, IntQT, true);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002775 std::string NSArrayFName("__NSContainer_literal");
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002776 FunctionDecl *NSArrayFD = SynthBlockInitFunctionDecl(NSArrayFName);
2777 DeclRefExpr *NSArrayDRE =
2778 new (Context) DeclRefExpr(NSArrayFD, false, NSArrayFType, VK_RValue,
2779 SourceLocation());
2780
2781 SmallVector<Expr*, 16> InitExprs;
2782 unsigned NumElements = Exp->getNumElements();
2783 unsigned UnsignedIntSize =
2784 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2785 Expr *count = IntegerLiteral::Create(*Context,
2786 llvm::APInt(UnsignedIntSize, NumElements),
2787 Context->UnsignedIntTy, SourceLocation());
2788 InitExprs.push_back(count);
2789 for (unsigned i = 0; i < NumElements; i++)
2790 InitExprs.push_back(Exp->getElement(i));
2791 Expr *NSArrayCallExpr =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002792 new (Context) CallExpr(*Context, NSArrayDRE, InitExprs,
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002793 NSArrayFType, VK_LValue, SourceLocation());
2794
2795 FieldDecl *ARRFD = FieldDecl::Create(*Context, 0, SourceLocation(),
2796 SourceLocation(),
2797 &Context->Idents.get("arr"),
2798 Context->getPointerType(Context->VoidPtrTy), 0,
2799 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00002800 ICIS_NoInit);
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002801 MemberExpr *ArrayLiteralME =
2802 new (Context) MemberExpr(NSArrayCallExpr, false, ARRFD,
2803 SourceLocation(),
2804 ARRFD->getType(), VK_LValue,
2805 OK_Ordinary);
2806 QualType ConstIdT = Context->getObjCIdType().withConst();
2807 CStyleCastExpr * ArrayLiteralObjects =
2808 NoTypeInfoCStyleCastExpr(Context,
2809 Context->getPointerType(ConstIdT),
2810 CK_BitCast,
2811 ArrayLiteralME);
2812
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002813 // Synthesize a call to objc_msgSend().
2814 SmallVector<Expr*, 32> MsgExprs;
2815 SmallVector<Expr*, 4> ClsExprs;
2816 QualType argType = Context->getPointerType(Context->CharTy);
2817 QualType expType = Exp->getType();
2818
2819 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2820 ObjCInterfaceDecl *Class =
2821 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2822
2823 IdentifierInfo *clsName = Class->getIdentifier();
2824 ClsExprs.push_back(StringLiteral::Create(*Context,
2825 clsName->getName(),
2826 StringLiteral::Ascii, false,
2827 argType, SourceLocation()));
2828 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2829 &ClsExprs[0],
2830 ClsExprs.size(),
2831 StartLoc, EndLoc);
2832 MsgExprs.push_back(Cls);
2833
2834 // Create a call to sel_registerName("arrayWithObjects:count:").
2835 // it will be the 2nd argument.
2836 SmallVector<Expr*, 4> SelExprs;
2837 ObjCMethodDecl *ArrayMethod = Exp->getArrayWithObjectsMethod();
2838 SelExprs.push_back(StringLiteral::Create(*Context,
2839 ArrayMethod->getSelector().getAsString(),
2840 StringLiteral::Ascii, false,
2841 argType, SourceLocation()));
2842 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2843 &SelExprs[0], SelExprs.size(),
2844 StartLoc, EndLoc);
2845 MsgExprs.push_back(SelExp);
2846
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002847 // (const id [])objects
2848 MsgExprs.push_back(ArrayLiteralObjects);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002849
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002850 // (NSUInteger)cnt
2851 Expr *cnt = IntegerLiteral::Create(*Context,
2852 llvm::APInt(UnsignedIntSize, NumElements),
2853 Context->UnsignedIntTy, SourceLocation());
2854 MsgExprs.push_back(cnt);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002855
2856
2857 SmallVector<QualType, 4> ArgTypes;
2858 ArgTypes.push_back(Context->getObjCIdType());
2859 ArgTypes.push_back(Context->getObjCSelType());
2860 for (ObjCMethodDecl::param_iterator PI = ArrayMethod->param_begin(),
2861 E = ArrayMethod->param_end(); PI != E; ++PI)
2862 ArgTypes.push_back((*PI)->getType());
2863
2864 QualType returnType = Exp->getType();
2865 // Get the type, we will need to reference it in a couple spots.
2866 QualType msgSendType = MsgSendFlavor->getType();
2867
2868 // Create a reference to the objc_msgSend() declaration.
2869 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2870 VK_LValue, SourceLocation());
2871
2872 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2873 Context->getPointerType(Context->VoidTy),
2874 CK_BitCast, DRE);
2875
2876 // Now do the "normal" pointer to function cast.
2877 QualType castType =
Jordan Rosebea522f2013-03-08 21:51:21 +00002878 getSimpleFunctionType(returnType, ArgTypes, ArrayMethod->isVariadic());
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002879 castType = Context->getPointerType(castType);
2880 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2881 cast);
2882
2883 // Don't forget the parens to enforce the proper binding.
2884 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2885
2886 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002887 CallExpr *CE = new (Context) CallExpr(*Context, PE, MsgExprs,
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002888 FT->getResultType(), VK_RValue,
2889 EndLoc);
2890 ReplaceStmt(Exp, CE);
2891 return CE;
2892}
2893
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002894Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp) {
2895 // synthesize declaration of helper functions needed in this routine.
2896 if (!SelGetUidFunctionDecl)
2897 SynthSelGetUidFunctionDecl();
2898 // use objc_msgSend() for all.
2899 if (!MsgSendFunctionDecl)
2900 SynthMsgSendFunctionDecl();
2901 if (!GetClassFunctionDecl)
2902 SynthGetClassFunctionDecl();
2903
2904 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2905 SourceLocation StartLoc = Exp->getLocStart();
2906 SourceLocation EndLoc = Exp->getLocEnd();
2907
2908 // Build the expression: __NSContainer_literal(int, ...).arr
2909 QualType IntQT = Context->IntTy;
2910 QualType NSDictFType =
Jordan Rosebea522f2013-03-08 21:51:21 +00002911 getSimpleFunctionType(Context->VoidTy, IntQT, true);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002912 std::string NSDictFName("__NSContainer_literal");
2913 FunctionDecl *NSDictFD = SynthBlockInitFunctionDecl(NSDictFName);
2914 DeclRefExpr *NSDictDRE =
2915 new (Context) DeclRefExpr(NSDictFD, false, NSDictFType, VK_RValue,
2916 SourceLocation());
2917
2918 SmallVector<Expr*, 16> KeyExprs;
2919 SmallVector<Expr*, 16> ValueExprs;
2920
2921 unsigned NumElements = Exp->getNumElements();
2922 unsigned UnsignedIntSize =
2923 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2924 Expr *count = IntegerLiteral::Create(*Context,
2925 llvm::APInt(UnsignedIntSize, NumElements),
2926 Context->UnsignedIntTy, SourceLocation());
2927 KeyExprs.push_back(count);
2928 ValueExprs.push_back(count);
2929 for (unsigned i = 0; i < NumElements; i++) {
2930 ObjCDictionaryElement Element = Exp->getKeyValueElement(i);
2931 KeyExprs.push_back(Element.Key);
2932 ValueExprs.push_back(Element.Value);
2933 }
2934
2935 // (const id [])objects
2936 Expr *NSValueCallExpr =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002937 new (Context) CallExpr(*Context, NSDictDRE, ValueExprs,
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002938 NSDictFType, VK_LValue, SourceLocation());
2939
2940 FieldDecl *ARRFD = FieldDecl::Create(*Context, 0, SourceLocation(),
2941 SourceLocation(),
2942 &Context->Idents.get("arr"),
2943 Context->getPointerType(Context->VoidPtrTy), 0,
2944 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00002945 ICIS_NoInit);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002946 MemberExpr *DictLiteralValueME =
2947 new (Context) MemberExpr(NSValueCallExpr, false, ARRFD,
2948 SourceLocation(),
2949 ARRFD->getType(), VK_LValue,
2950 OK_Ordinary);
2951 QualType ConstIdT = Context->getObjCIdType().withConst();
2952 CStyleCastExpr * DictValueObjects =
2953 NoTypeInfoCStyleCastExpr(Context,
2954 Context->getPointerType(ConstIdT),
2955 CK_BitCast,
2956 DictLiteralValueME);
2957 // (const id <NSCopying> [])keys
2958 Expr *NSKeyCallExpr =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002959 new (Context) CallExpr(*Context, NSDictDRE, KeyExprs,
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002960 NSDictFType, VK_LValue, SourceLocation());
2961
2962 MemberExpr *DictLiteralKeyME =
2963 new (Context) MemberExpr(NSKeyCallExpr, false, ARRFD,
2964 SourceLocation(),
2965 ARRFD->getType(), VK_LValue,
2966 OK_Ordinary);
2967
2968 CStyleCastExpr * DictKeyObjects =
2969 NoTypeInfoCStyleCastExpr(Context,
2970 Context->getPointerType(ConstIdT),
2971 CK_BitCast,
2972 DictLiteralKeyME);
2973
2974
2975
2976 // Synthesize a call to objc_msgSend().
2977 SmallVector<Expr*, 32> MsgExprs;
2978 SmallVector<Expr*, 4> ClsExprs;
2979 QualType argType = Context->getPointerType(Context->CharTy);
2980 QualType expType = Exp->getType();
2981
2982 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2983 ObjCInterfaceDecl *Class =
2984 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2985
2986 IdentifierInfo *clsName = Class->getIdentifier();
2987 ClsExprs.push_back(StringLiteral::Create(*Context,
2988 clsName->getName(),
2989 StringLiteral::Ascii, false,
2990 argType, SourceLocation()));
2991 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2992 &ClsExprs[0],
2993 ClsExprs.size(),
2994 StartLoc, EndLoc);
2995 MsgExprs.push_back(Cls);
2996
2997 // Create a call to sel_registerName("arrayWithObjects:count:").
2998 // it will be the 2nd argument.
2999 SmallVector<Expr*, 4> SelExprs;
3000 ObjCMethodDecl *DictMethod = Exp->getDictWithObjectsMethod();
3001 SelExprs.push_back(StringLiteral::Create(*Context,
3002 DictMethod->getSelector().getAsString(),
3003 StringLiteral::Ascii, false,
3004 argType, SourceLocation()));
3005 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
3006 &SelExprs[0], SelExprs.size(),
3007 StartLoc, EndLoc);
3008 MsgExprs.push_back(SelExp);
3009
3010 // (const id [])objects
3011 MsgExprs.push_back(DictValueObjects);
3012
3013 // (const id <NSCopying> [])keys
3014 MsgExprs.push_back(DictKeyObjects);
3015
3016 // (NSUInteger)cnt
3017 Expr *cnt = IntegerLiteral::Create(*Context,
3018 llvm::APInt(UnsignedIntSize, NumElements),
3019 Context->UnsignedIntTy, SourceLocation());
3020 MsgExprs.push_back(cnt);
3021
3022
3023 SmallVector<QualType, 8> ArgTypes;
3024 ArgTypes.push_back(Context->getObjCIdType());
3025 ArgTypes.push_back(Context->getObjCSelType());
3026 for (ObjCMethodDecl::param_iterator PI = DictMethod->param_begin(),
3027 E = DictMethod->param_end(); PI != E; ++PI) {
3028 QualType T = (*PI)->getType();
3029 if (const PointerType* PT = T->getAs<PointerType>()) {
3030 QualType PointeeTy = PT->getPointeeType();
3031 convertToUnqualifiedObjCType(PointeeTy);
3032 T = Context->getPointerType(PointeeTy);
3033 }
3034 ArgTypes.push_back(T);
3035 }
3036
3037 QualType returnType = Exp->getType();
3038 // Get the type, we will need to reference it in a couple spots.
3039 QualType msgSendType = MsgSendFlavor->getType();
3040
3041 // Create a reference to the objc_msgSend() declaration.
3042 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
3043 VK_LValue, SourceLocation());
3044
3045 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
3046 Context->getPointerType(Context->VoidTy),
3047 CK_BitCast, DRE);
3048
3049 // Now do the "normal" pointer to function cast.
3050 QualType castType =
Jordan Rosebea522f2013-03-08 21:51:21 +00003051 getSimpleFunctionType(returnType, ArgTypes, DictMethod->isVariadic());
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00003052 castType = Context->getPointerType(castType);
3053 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3054 cast);
3055
3056 // Don't forget the parens to enforce the proper binding.
3057 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3058
3059 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003060 CallExpr *CE = new (Context) CallExpr(*Context, PE, MsgExprs,
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00003061 FT->getResultType(), VK_RValue,
3062 EndLoc);
3063 ReplaceStmt(Exp, CE);
3064 return CE;
3065}
3066
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003067// struct __rw_objc_super {
3068// struct objc_object *object; struct objc_object *superClass;
3069// };
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003070QualType RewriteModernObjC::getSuperStructType() {
3071 if (!SuperStructDecl) {
3072 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3073 SourceLocation(), SourceLocation(),
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003074 &Context->Idents.get("__rw_objc_super"));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003075 QualType FieldTypes[2];
3076
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003077 // struct objc_object *object;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003078 FieldTypes[0] = Context->getObjCIdType();
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003079 // struct objc_object *superClass;
3080 FieldTypes[1] = Context->getObjCIdType();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003081
3082 // Create fields
3083 for (unsigned i = 0; i < 2; ++i) {
3084 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
3085 SourceLocation(),
3086 SourceLocation(), 0,
3087 FieldTypes[i], 0,
3088 /*BitWidth=*/0,
3089 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00003090 ICIS_NoInit));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003091 }
3092
3093 SuperStructDecl->completeDefinition();
3094 }
3095 return Context->getTagDeclType(SuperStructDecl);
3096}
3097
3098QualType RewriteModernObjC::getConstantStringStructType() {
3099 if (!ConstantStringDecl) {
3100 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3101 SourceLocation(), SourceLocation(),
3102 &Context->Idents.get("__NSConstantStringImpl"));
3103 QualType FieldTypes[4];
3104
3105 // struct objc_object *receiver;
3106 FieldTypes[0] = Context->getObjCIdType();
3107 // int flags;
3108 FieldTypes[1] = Context->IntTy;
3109 // char *str;
3110 FieldTypes[2] = Context->getPointerType(Context->CharTy);
3111 // long length;
3112 FieldTypes[3] = Context->LongTy;
3113
3114 // Create fields
3115 for (unsigned i = 0; i < 4; ++i) {
3116 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
3117 ConstantStringDecl,
3118 SourceLocation(),
3119 SourceLocation(), 0,
3120 FieldTypes[i], 0,
3121 /*BitWidth=*/0,
3122 /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00003123 ICIS_NoInit));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003124 }
3125
3126 ConstantStringDecl->completeDefinition();
3127 }
3128 return Context->getTagDeclType(ConstantStringDecl);
3129}
3130
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003131/// getFunctionSourceLocation - returns start location of a function
3132/// definition. Complication arises when function has declared as
3133/// extern "C" or extern "C" {...}
3134static SourceLocation getFunctionSourceLocation (RewriteModernObjC &R,
3135 FunctionDecl *FD) {
3136 if (FD->isExternC() && !FD->isMain()) {
3137 const DeclContext *DC = FD->getDeclContext();
3138 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3139 // if it is extern "C" {...}, return function decl's own location.
3140 if (!LSD->getRBraceLoc().isValid())
3141 return LSD->getExternLoc();
3142 }
Rafael Espindolad2615cc2013-04-03 19:27:57 +00003143 if (FD->getStorageClass() != SC_None)
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003144 R.RewriteBlockLiteralFunctionDecl(FD);
3145 return FD->getTypeSpecStartLoc();
3146}
3147
Fariborz Jahanian96205962012-11-06 17:30:23 +00003148void RewriteModernObjC::RewriteLineDirective(const Decl *D) {
3149
3150 SourceLocation Location = D->getLocation();
3151
Fariborz Jahanianada71912013-02-08 00:27:34 +00003152 if (Location.isFileID() && GenerateLineInfo) {
Fariborz Jahanian3b45ca92012-11-07 18:15:53 +00003153 std::string LineString("\n#line ");
Fariborz Jahanian96205962012-11-06 17:30:23 +00003154 PresumedLoc PLoc = SM->getPresumedLoc(Location);
3155 LineString += utostr(PLoc.getLine());
3156 LineString += " \"";
NAKAMURA Takumiba529a92012-11-06 22:45:31 +00003157 LineString += Lexer::Stringify(PLoc.getFilename());
Fariborz Jahanian96205962012-11-06 17:30:23 +00003158 if (isa<ObjCMethodDecl>(D))
3159 LineString += "\"";
3160 else LineString += "\"\n";
3161
3162 Location = D->getLocStart();
3163 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3164 if (FD->isExternC() && !FD->isMain()) {
3165 const DeclContext *DC = FD->getDeclContext();
3166 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3167 // if it is extern "C" {...}, return function decl's own location.
3168 if (!LSD->getRBraceLoc().isValid())
3169 Location = LSD->getExternLoc();
3170 }
3171 }
3172 InsertText(Location, LineString);
3173 }
3174}
3175
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003176/// SynthMsgSendStretCallExpr - This routine translates message expression
3177/// into a call to objc_msgSend_stret() entry point. Tricky part is that
3178/// nil check on receiver must be performed before calling objc_msgSend_stret.
3179/// MsgSendStretFlavor - function declaration objc_msgSend_stret(...)
3180/// msgSendType - function type of objc_msgSend_stret(...)
3181/// returnType - Result type of the method being synthesized.
3182/// ArgTypes - type of the arguments passed to objc_msgSend_stret, starting with receiver type.
3183/// MsgExprs - list of argument expressions being passed to objc_msgSend_stret,
3184/// starting with receiver.
3185/// Method - Method being rewritten.
3186Expr *RewriteModernObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003187 QualType returnType,
3188 SmallVectorImpl<QualType> &ArgTypes,
3189 SmallVectorImpl<Expr*> &MsgExprs,
3190 ObjCMethodDecl *Method) {
3191 // Now do the "normal" pointer to function cast.
Jordan Rosebea522f2013-03-08 21:51:21 +00003192 QualType castType = getSimpleFunctionType(returnType, ArgTypes,
3193 Method ? Method->isVariadic()
3194 : false);
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003195 castType = Context->getPointerType(castType);
3196
3197 // build type for containing the objc_msgSend_stret object.
3198 static unsigned stretCount=0;
3199 std::string name = "__Stret"; name += utostr(stretCount);
Fariborz Jahanian2ca5af22012-07-25 21:48:36 +00003200 std::string str =
3201 "extern \"C\" void * __cdecl memset(void *_Dst, int _Val, size_t _Size);\n";
Fariborz Jahanian426bb9c2013-09-09 19:59:59 +00003202 str += "namespace {\n";
Fariborz Jahanian2ca5af22012-07-25 21:48:36 +00003203 str += "struct "; str += name;
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003204 str += " {\n\t";
3205 str += name;
3206 str += "(id receiver, SEL sel";
3207 for (unsigned i = 2; i < ArgTypes.size(); i++) {
Fariborz Jahanian6734ec42012-06-29 19:55:46 +00003208 std::string ArgName = "arg"; ArgName += utostr(i);
3209 ArgTypes[i].getAsStringInternal(ArgName, Context->getPrintingPolicy());
3210 str += ", "; str += ArgName;
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003211 }
3212 // could be vararg.
3213 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
Fariborz Jahanian6734ec42012-06-29 19:55:46 +00003214 std::string ArgName = "arg"; ArgName += utostr(i);
3215 MsgExprs[i]->getType().getAsStringInternal(ArgName,
3216 Context->getPrintingPolicy());
3217 str += ", "; str += ArgName;
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003218 }
3219
3220 str += ") {\n";
Fariborz Jahanian426bb9c2013-09-09 19:59:59 +00003221 str += "\t unsigned size = sizeof(";
3222 str += returnType.getAsString(Context->getPrintingPolicy()); str += ");\n";
3223
3224 str += "\t if (size == 1 || size == 2 || size == 4 || size == 8)\n";
3225
3226 str += "\t s = (("; str += castType.getAsString(Context->getPrintingPolicy());
3227 str += ")(void *)objc_msgSend)(receiver, sel";
3228 for (unsigned i = 2; i < ArgTypes.size(); i++) {
3229 str += ", arg"; str += utostr(i);
3230 }
3231 // could be vararg.
3232 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3233 str += ", arg"; str += utostr(i);
3234 }
3235 str+= ");\n";
3236
3237 str += "\t else if (receiver == 0)\n";
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003238 str += "\t memset((void*)&s, 0, sizeof(s));\n";
3239 str += "\t else\n";
Fariborz Jahanian426bb9c2013-09-09 19:59:59 +00003240
3241
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003242 str += "\t s = (("; str += castType.getAsString(Context->getPrintingPolicy());
3243 str += ")(void *)objc_msgSend_stret)(receiver, sel";
3244 for (unsigned i = 2; i < ArgTypes.size(); i++) {
3245 str += ", arg"; str += utostr(i);
3246 }
3247 // could be vararg.
3248 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3249 str += ", arg"; str += utostr(i);
3250 }
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003251 str += ");\n";
Fariborz Jahanian426bb9c2013-09-09 19:59:59 +00003252
3253
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003254 str += "\t}\n";
3255 str += "\t"; str += returnType.getAsString(Context->getPrintingPolicy());
3256 str += " s;\n";
Fariborz Jahanian426bb9c2013-09-09 19:59:59 +00003257 str += "};\n};\n\n";
Fariborz Jahaniana6e5a6e2012-08-21 18:56:50 +00003258 SourceLocation FunLocStart;
3259 if (CurFunctionDef)
3260 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
3261 else {
3262 assert(CurMethodDef && "SynthMsgSendStretCallExpr - CurMethodDef is null");
3263 FunLocStart = CurMethodDef->getLocStart();
3264 }
3265
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003266 InsertText(FunLocStart, str);
3267 ++stretCount;
3268
3269 // AST for __Stretn(receiver, args).s;
3270 IdentifierInfo *ID = &Context->Idents.get(name);
3271 FunctionDecl *FD = FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
Chad Rosiere3b29882013-01-04 22:40:33 +00003272 SourceLocation(), ID, castType, 0,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00003273 SC_Extern, false, false);
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003274 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, castType, VK_RValue,
3275 SourceLocation());
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003276 CallExpr *STCE = new (Context) CallExpr(*Context, DRE, MsgExprs,
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003277 castType, VK_LValue, SourceLocation());
3278
3279 FieldDecl *FieldD = FieldDecl::Create(*Context, 0, SourceLocation(),
3280 SourceLocation(),
3281 &Context->Idents.get("s"),
3282 returnType, 0,
3283 /*BitWidth=*/0, /*Mutable=*/true,
3284 ICIS_NoInit);
3285 MemberExpr *ME = new (Context) MemberExpr(STCE, false, FieldD, SourceLocation(),
3286 FieldD->getType(), VK_LValue,
3287 OK_Ordinary);
3288
3289 return ME;
3290}
3291
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003292Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
3293 SourceLocation StartLoc,
3294 SourceLocation EndLoc) {
3295 if (!SelGetUidFunctionDecl)
3296 SynthSelGetUidFunctionDecl();
3297 if (!MsgSendFunctionDecl)
3298 SynthMsgSendFunctionDecl();
3299 if (!MsgSendSuperFunctionDecl)
3300 SynthMsgSendSuperFunctionDecl();
3301 if (!MsgSendStretFunctionDecl)
3302 SynthMsgSendStretFunctionDecl();
3303 if (!MsgSendSuperStretFunctionDecl)
3304 SynthMsgSendSuperStretFunctionDecl();
3305 if (!MsgSendFpretFunctionDecl)
3306 SynthMsgSendFpretFunctionDecl();
3307 if (!GetClassFunctionDecl)
3308 SynthGetClassFunctionDecl();
3309 if (!GetSuperClassFunctionDecl)
3310 SynthGetSuperClassFunctionDecl();
3311 if (!GetMetaClassFunctionDecl)
3312 SynthGetMetaClassFunctionDecl();
3313
3314 // default to objc_msgSend().
3315 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
3316 // May need to use objc_msgSend_stret() as well.
3317 FunctionDecl *MsgSendStretFlavor = 0;
3318 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
3319 QualType resultType = mDecl->getResultType();
3320 if (resultType->isRecordType())
3321 MsgSendStretFlavor = MsgSendStretFunctionDecl;
3322 else if (resultType->isRealFloatingType())
3323 MsgSendFlavor = MsgSendFpretFunctionDecl;
3324 }
3325
3326 // Synthesize a call to objc_msgSend().
3327 SmallVector<Expr*, 8> MsgExprs;
3328 switch (Exp->getReceiverKind()) {
3329 case ObjCMessageExpr::SuperClass: {
3330 MsgSendFlavor = MsgSendSuperFunctionDecl;
3331 if (MsgSendStretFlavor)
3332 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3333 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3334
3335 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3336
3337 SmallVector<Expr*, 4> InitExprs;
3338
3339 // set the receiver to self, the first argument to all methods.
3340 InitExprs.push_back(
3341 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3342 CK_BitCast,
3343 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00003344 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003345 Context->getObjCIdType(),
3346 VK_RValue,
3347 SourceLocation()))
3348 ); // set the 'receiver'.
3349
3350 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3351 SmallVector<Expr*, 8> ClsExprs;
3352 QualType argType = Context->getPointerType(Context->CharTy);
3353 ClsExprs.push_back(StringLiteral::Create(*Context,
3354 ClassDecl->getIdentifier()->getName(),
3355 StringLiteral::Ascii, false,
3356 argType, SourceLocation()));
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003357 // (Class)objc_getClass("CurrentClass")
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003358 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
3359 &ClsExprs[0],
3360 ClsExprs.size(),
3361 StartLoc,
3362 EndLoc);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003363 ClsExprs.clear();
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003364 ClsExprs.push_back(Cls);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003365 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3366 &ClsExprs[0], ClsExprs.size(),
3367 StartLoc, EndLoc);
3368
3369 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3370 // To turn off a warning, type-cast to 'id'
3371 InitExprs.push_back( // set 'super class', using class_getSuperclass().
3372 NoTypeInfoCStyleCastExpr(Context,
3373 Context->getObjCIdType(),
3374 CK_BitCast, Cls));
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003375 // struct __rw_objc_super
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003376 QualType superType = getSuperStructType();
3377 Expr *SuperRep;
3378
3379 if (LangOpts.MicrosoftExt) {
Benjamin Kramere5753592013-09-09 14:48:42 +00003380 SynthSuperConstructorFunctionDecl();
3381 // Simulate a constructor call...
3382 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperConstructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00003383 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003384 SourceLocation());
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003385 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003386 superType, VK_LValue,
3387 SourceLocation());
3388 // The code for super is a little tricky to prevent collision with
3389 // the structure definition in the header. The rewriter has it's own
3390 // internal definition (__rw_objc_super) that is uses. This is why
3391 // we need the cast below. For example:
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003392 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003393 //
3394 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3395 Context->getPointerType(SuperRep->getType()),
3396 VK_RValue, OK_Ordinary,
3397 SourceLocation());
3398 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3399 Context->getPointerType(superType),
3400 CK_BitCast, SuperRep);
3401 } else {
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003402 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003403 InitListExpr *ILE =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003404 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003405 SourceLocation());
3406 TypeSourceInfo *superTInfo
3407 = Context->getTrivialTypeSourceInfo(superType);
3408 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3409 superType, VK_LValue,
3410 ILE, false);
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003411 // struct __rw_objc_super *
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003412 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3413 Context->getPointerType(SuperRep->getType()),
3414 VK_RValue, OK_Ordinary,
3415 SourceLocation());
3416 }
3417 MsgExprs.push_back(SuperRep);
3418 break;
3419 }
3420
3421 case ObjCMessageExpr::Class: {
3422 SmallVector<Expr*, 8> ClsExprs;
3423 QualType argType = Context->getPointerType(Context->CharTy);
3424 ObjCInterfaceDecl *Class
3425 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
3426 IdentifierInfo *clsName = Class->getIdentifier();
3427 ClsExprs.push_back(StringLiteral::Create(*Context,
3428 clsName->getName(),
3429 StringLiteral::Ascii, false,
3430 argType, SourceLocation()));
3431 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3432 &ClsExprs[0],
3433 ClsExprs.size(),
3434 StartLoc, EndLoc);
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003435 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
3436 Context->getObjCIdType(),
3437 CK_BitCast, Cls);
3438 MsgExprs.push_back(ArgExpr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003439 break;
3440 }
3441
3442 case ObjCMessageExpr::SuperInstance:{
3443 MsgSendFlavor = MsgSendSuperFunctionDecl;
3444 if (MsgSendStretFlavor)
3445 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3446 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3447 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3448 SmallVector<Expr*, 4> InitExprs;
3449
3450 InitExprs.push_back(
3451 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3452 CK_BitCast,
3453 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00003454 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003455 Context->getObjCIdType(),
3456 VK_RValue, SourceLocation()))
3457 ); // set the 'receiver'.
3458
3459 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3460 SmallVector<Expr*, 8> ClsExprs;
3461 QualType argType = Context->getPointerType(Context->CharTy);
3462 ClsExprs.push_back(StringLiteral::Create(*Context,
3463 ClassDecl->getIdentifier()->getName(),
3464 StringLiteral::Ascii, false, argType,
3465 SourceLocation()));
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003466 // (Class)objc_getClass("CurrentClass")
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003467 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3468 &ClsExprs[0],
3469 ClsExprs.size(),
3470 StartLoc, EndLoc);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003471 ClsExprs.clear();
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003472 ClsExprs.push_back(Cls);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003473 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3474 &ClsExprs[0], ClsExprs.size(),
3475 StartLoc, EndLoc);
3476
3477 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3478 // To turn off a warning, type-cast to 'id'
3479 InitExprs.push_back(
3480 // set 'super class', using class_getSuperclass().
3481 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3482 CK_BitCast, Cls));
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003483 // struct __rw_objc_super
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003484 QualType superType = getSuperStructType();
3485 Expr *SuperRep;
3486
3487 if (LangOpts.MicrosoftExt) {
Benjamin Kramere5753592013-09-09 14:48:42 +00003488 SynthSuperConstructorFunctionDecl();
3489 // Simulate a constructor call...
3490 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperConstructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00003491 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003492 SourceLocation());
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003493 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003494 superType, VK_LValue, SourceLocation());
3495 // The code for super is a little tricky to prevent collision with
3496 // the structure definition in the header. The rewriter has it's own
3497 // internal definition (__rw_objc_super) that is uses. This is why
3498 // we need the cast below. For example:
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003499 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003500 //
3501 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3502 Context->getPointerType(SuperRep->getType()),
3503 VK_RValue, OK_Ordinary,
3504 SourceLocation());
3505 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3506 Context->getPointerType(superType),
3507 CK_BitCast, SuperRep);
3508 } else {
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003509 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003510 InitListExpr *ILE =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003511 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003512 SourceLocation());
3513 TypeSourceInfo *superTInfo
3514 = Context->getTrivialTypeSourceInfo(superType);
3515 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3516 superType, VK_RValue, ILE,
3517 false);
3518 }
3519 MsgExprs.push_back(SuperRep);
3520 break;
3521 }
3522
3523 case ObjCMessageExpr::Instance: {
3524 // Remove all type-casts because it may contain objc-style types; e.g.
3525 // Foo<Proto> *.
3526 Expr *recExpr = Exp->getInstanceReceiver();
3527 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
3528 recExpr = CE->getSubExpr();
3529 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
3530 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
3531 ? CK_BlockPointerToObjCPointerCast
3532 : CK_CPointerToObjCPointerCast;
3533
3534 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3535 CK, recExpr);
3536 MsgExprs.push_back(recExpr);
3537 break;
3538 }
3539 }
3540
3541 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
3542 SmallVector<Expr*, 8> SelExprs;
3543 QualType argType = Context->getPointerType(Context->CharTy);
3544 SelExprs.push_back(StringLiteral::Create(*Context,
3545 Exp->getSelector().getAsString(),
3546 StringLiteral::Ascii, false,
3547 argType, SourceLocation()));
3548 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
3549 &SelExprs[0], SelExprs.size(),
3550 StartLoc,
3551 EndLoc);
3552 MsgExprs.push_back(SelExp);
3553
3554 // Now push any user supplied arguments.
3555 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
3556 Expr *userExpr = Exp->getArg(i);
3557 // Make all implicit casts explicit...ICE comes in handy:-)
3558 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
3559 // Reuse the ICE type, it is exactly what the doctor ordered.
3560 QualType type = ICE->getType();
3561 if (needToScanForQualifiers(type))
3562 type = Context->getObjCIdType();
3563 // Make sure we convert "type (^)(...)" to "type (*)(...)".
3564 (void)convertBlockPointerToFunctionPointer(type);
3565 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
3566 CastKind CK;
3567 if (SubExpr->getType()->isIntegralType(*Context) &&
3568 type->isBooleanType()) {
3569 CK = CK_IntegralToBoolean;
3570 } else if (type->isObjCObjectPointerType()) {
3571 if (SubExpr->getType()->isBlockPointerType()) {
3572 CK = CK_BlockPointerToObjCPointerCast;
3573 } else if (SubExpr->getType()->isPointerType()) {
3574 CK = CK_CPointerToObjCPointerCast;
3575 } else {
3576 CK = CK_BitCast;
3577 }
3578 } else {
3579 CK = CK_BitCast;
3580 }
3581
3582 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
3583 }
3584 // Make id<P...> cast into an 'id' cast.
3585 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
3586 if (CE->getType()->isObjCQualifiedIdType()) {
3587 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
3588 userExpr = CE->getSubExpr();
3589 CastKind CK;
3590 if (userExpr->getType()->isIntegralType(*Context)) {
3591 CK = CK_IntegralToPointer;
3592 } else if (userExpr->getType()->isBlockPointerType()) {
3593 CK = CK_BlockPointerToObjCPointerCast;
3594 } else if (userExpr->getType()->isPointerType()) {
3595 CK = CK_CPointerToObjCPointerCast;
3596 } else {
3597 CK = CK_BitCast;
3598 }
3599 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3600 CK, userExpr);
3601 }
3602 }
3603 MsgExprs.push_back(userExpr);
3604 // We've transferred the ownership to MsgExprs. For now, we *don't* null
3605 // out the argument in the original expression (since we aren't deleting
3606 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
3607 //Exp->setArg(i, 0);
3608 }
3609 // Generate the funky cast.
3610 CastExpr *cast;
3611 SmallVector<QualType, 8> ArgTypes;
3612 QualType returnType;
3613
3614 // Push 'id' and 'SEL', the 2 implicit arguments.
3615 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3616 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3617 else
3618 ArgTypes.push_back(Context->getObjCIdType());
3619 ArgTypes.push_back(Context->getObjCSelType());
3620 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
3621 // Push any user argument types.
3622 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
3623 E = OMD->param_end(); PI != E; ++PI) {
3624 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
3625 ? Context->getObjCIdType()
3626 : (*PI)->getType();
3627 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3628 (void)convertBlockPointerToFunctionPointer(t);
3629 ArgTypes.push_back(t);
3630 }
3631 returnType = Exp->getType();
3632 convertToUnqualifiedObjCType(returnType);
3633 (void)convertBlockPointerToFunctionPointer(returnType);
3634 } else {
3635 returnType = Context->getObjCIdType();
3636 }
3637 // Get the type, we will need to reference it in a couple spots.
3638 QualType msgSendType = MsgSendFlavor->getType();
3639
3640 // Create a reference to the objc_msgSend() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00003641 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003642 VK_LValue, SourceLocation());
3643
3644 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
3645 // If we don't do this cast, we get the following bizarre warning/note:
3646 // xx.m:13: warning: function called through a non-compatible type
3647 // xx.m:13: note: if this code is reached, the program will abort
3648 cast = NoTypeInfoCStyleCastExpr(Context,
3649 Context->getPointerType(Context->VoidTy),
3650 CK_BitCast, DRE);
3651
3652 // Now do the "normal" pointer to function cast.
Jordan Rosebea522f2013-03-08 21:51:21 +00003653 // If we don't have a method decl, force a variadic cast.
3654 const ObjCMethodDecl *MD = Exp->getMethodDecl();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003655 QualType castType =
Jordan Rosebea522f2013-03-08 21:51:21 +00003656 getSimpleFunctionType(returnType, ArgTypes, MD ? MD->isVariadic() : true);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003657 castType = Context->getPointerType(castType);
3658 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3659 cast);
3660
3661 // Don't forget the parens to enforce the proper binding.
3662 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3663
3664 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003665 CallExpr *CE = new (Context) CallExpr(*Context, PE, MsgExprs,
3666 FT->getResultType(), VK_RValue, EndLoc);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003667 Stmt *ReplacingStmt = CE;
3668 if (MsgSendStretFlavor) {
3669 // We have the method which returns a struct/union. Must also generate
3670 // call to objc_msgSend_stret and hang both varieties on a conditional
3671 // expression which dictate which one to envoke depending on size of
3672 // method's return type.
3673
Fariborz Jahanian426bb9c2013-09-09 19:59:59 +00003674 Expr *STCE = SynthMsgSendStretCallExpr(MsgSendStretFlavor,
3675 returnType,
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003676 ArgTypes, MsgExprs,
3677 Exp->getMethodDecl());
Fariborz Jahanian426bb9c2013-09-09 19:59:59 +00003678 ReplacingStmt = STCE;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003679 }
3680 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3681 return ReplacingStmt;
3682}
3683
3684Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
3685 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3686 Exp->getLocEnd());
3687
3688 // Now do the actual rewrite.
3689 ReplaceStmt(Exp, ReplacingStmt);
3690
3691 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3692 return ReplacingStmt;
3693}
3694
3695// typedef struct objc_object Protocol;
3696QualType RewriteModernObjC::getProtocolType() {
3697 if (!ProtocolTypeDecl) {
3698 TypeSourceInfo *TInfo
3699 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3700 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
3701 SourceLocation(), SourceLocation(),
3702 &Context->Idents.get("Protocol"),
3703 TInfo);
3704 }
3705 return Context->getTypeDeclType(ProtocolTypeDecl);
3706}
3707
3708/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3709/// a synthesized/forward data reference (to the protocol's metadata).
3710/// The forward references (and metadata) are generated in
3711/// RewriteModernObjC::HandleTranslationUnit().
3712Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00003713 std::string Name = "_OBJC_PROTOCOL_REFERENCE_$_" +
3714 Exp->getProtocol()->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003715 IdentifierInfo *ID = &Context->Idents.get(Name);
3716 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
3717 SourceLocation(), ID, getProtocolType(), 0,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00003718 SC_Extern);
John McCallf4b88a42012-03-10 09:33:50 +00003719 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
3720 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003721 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
3722 Context->getPointerType(DRE->getType()),
3723 VK_RValue, OK_Ordinary, SourceLocation());
3724 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
3725 CK_BitCast,
3726 DerefExpr);
3727 ReplaceStmt(Exp, castExpr);
3728 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3729 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3730 return castExpr;
3731
3732}
3733
3734bool RewriteModernObjC::BufferContainsPPDirectives(const char *startBuf,
3735 const char *endBuf) {
3736 while (startBuf < endBuf) {
3737 if (*startBuf == '#') {
3738 // Skip whitespace.
3739 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3740 ;
3741 if (!strncmp(startBuf, "if", strlen("if")) ||
3742 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3743 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3744 !strncmp(startBuf, "define", strlen("define")) ||
3745 !strncmp(startBuf, "undef", strlen("undef")) ||
3746 !strncmp(startBuf, "else", strlen("else")) ||
3747 !strncmp(startBuf, "elif", strlen("elif")) ||
3748 !strncmp(startBuf, "endif", strlen("endif")) ||
3749 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3750 !strncmp(startBuf, "include", strlen("include")) ||
3751 !strncmp(startBuf, "import", strlen("import")) ||
3752 !strncmp(startBuf, "include_next", strlen("include_next")))
3753 return true;
3754 }
3755 startBuf++;
3756 }
3757 return false;
3758}
3759
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003760/// IsTagDefinedInsideClass - This routine checks that a named tagged type
3761/// is defined inside an objective-c class. If so, it returns true.
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00003762bool RewriteModernObjC::IsTagDefinedInsideClass(ObjCContainerDecl *IDecl,
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003763 TagDecl *Tag,
3764 bool &IsNamedDefinition) {
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003765 if (!IDecl)
3766 return false;
3767 SourceLocation TagLocation;
3768 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) {
3769 RD = RD->getDefinition();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003770 if (!RD || !RD->getDeclName().getAsIdentifierInfo())
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003771 return false;
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003772 IsNamedDefinition = true;
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003773 TagLocation = RD->getLocation();
3774 return Context->getSourceManager().isBeforeInTranslationUnit(
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003775 IDecl->getLocation(), TagLocation);
3776 }
3777 if (EnumDecl *ED = dyn_cast<EnumDecl>(Tag)) {
3778 if (!ED || !ED->getDeclName().getAsIdentifierInfo())
3779 return false;
3780 IsNamedDefinition = true;
3781 TagLocation = ED->getLocation();
3782 return Context->getSourceManager().isBeforeInTranslationUnit(
3783 IDecl->getLocation(), TagLocation);
3784
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003785 }
3786 return false;
3787}
3788
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003789/// RewriteObjCFieldDeclType - This routine rewrites a type into the buffer.
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003790/// It handles elaborated types, as well as enum types in the process.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003791bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type,
3792 std::string &Result) {
Fariborz Jahanianf5eac482012-05-02 17:34:59 +00003793 if (isa<TypedefType>(Type)) {
3794 Result += "\t";
3795 return false;
3796 }
3797
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003798 if (Type->isArrayType()) {
3799 QualType ElemTy = Context->getBaseElementType(Type);
3800 return RewriteObjCFieldDeclType(ElemTy, Result);
3801 }
3802 else if (Type->isRecordType()) {
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003803 RecordDecl *RD = Type->getAs<RecordType>()->getDecl();
3804 if (RD->isCompleteDefinition()) {
3805 if (RD->isStruct())
3806 Result += "\n\tstruct ";
3807 else if (RD->isUnion())
3808 Result += "\n\tunion ";
3809 else
3810 assert(false && "class not allowed as an ivar type");
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003811
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003812 Result += RD->getName();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003813 if (GlobalDefinedTags.count(RD)) {
3814 // struct/union is defined globally, use it.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003815 Result += " ";
3816 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003817 }
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003818 Result += " {\n";
3819 for (RecordDecl::field_iterator i = RD->field_begin(),
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003820 e = RD->field_end(); i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00003821 FieldDecl *FD = *i;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003822 RewriteObjCFieldDecl(FD, Result);
3823 }
3824 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003825 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003826 }
3827 }
3828 else if (Type->isEnumeralType()) {
3829 EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3830 if (ED->isCompleteDefinition()) {
3831 Result += "\n\tenum ";
3832 Result += ED->getName();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003833 if (GlobalDefinedTags.count(ED)) {
3834 // Enum is globall defined, use it.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003835 Result += " ";
3836 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003837 }
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003838
3839 Result += " {\n";
3840 for (EnumDecl::enumerator_iterator EC = ED->enumerator_begin(),
3841 ECEnd = ED->enumerator_end(); EC != ECEnd; ++EC) {
3842 Result += "\t"; Result += EC->getName(); Result += " = ";
3843 llvm::APSInt Val = EC->getInitVal();
3844 Result += Val.toString(10);
3845 Result += ",\n";
3846 }
3847 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003848 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003849 }
3850 }
3851
3852 Result += "\t";
3853 convertObjCTypeToCStyleType(Type);
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003854 return false;
3855}
3856
3857
3858/// RewriteObjCFieldDecl - This routine rewrites a field into the buffer.
3859/// It handles elaborated types, as well as enum types in the process.
3860void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl,
3861 std::string &Result) {
3862 QualType Type = fieldDecl->getType();
3863 std::string Name = fieldDecl->getNameAsString();
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003864
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003865 bool EleboratedType = RewriteObjCFieldDeclType(Type, Result);
3866 if (!EleboratedType)
3867 Type.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003868 Result += Name;
3869 if (fieldDecl->isBitField()) {
3870 Result += " : "; Result += utostr(fieldDecl->getBitWidthValue(*Context));
3871 }
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003872 else if (EleboratedType && Type->isArrayType()) {
Eli Friedman6febf122012-12-13 01:43:21 +00003873 const ArrayType *AT = Context->getAsArrayType(Type);
3874 do {
3875 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003876 Result += "[";
3877 llvm::APInt Dim = CAT->getSize();
3878 Result += utostr(Dim.getZExtValue());
3879 Result += "]";
3880 }
Eli Friedman6febf122012-12-13 01:43:21 +00003881 AT = Context->getAsArrayType(AT->getElementType());
3882 } while (AT);
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003883 }
3884
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003885 Result += ";\n";
3886}
3887
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003888/// RewriteLocallyDefinedNamedAggregates - This routine rewrites locally defined
3889/// named aggregate types into the input buffer.
3890void RewriteModernObjC::RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
3891 std::string &Result) {
3892 QualType Type = fieldDecl->getType();
Fariborz Jahanianf5eac482012-05-02 17:34:59 +00003893 if (isa<TypedefType>(Type))
3894 return;
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003895 if (Type->isArrayType())
3896 Type = Context->getBaseElementType(Type);
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00003897 ObjCContainerDecl *IDecl =
3898 dyn_cast<ObjCContainerDecl>(fieldDecl->getDeclContext());
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003899
3900 TagDecl *TD = 0;
3901 if (Type->isRecordType()) {
3902 TD = Type->getAs<RecordType>()->getDecl();
3903 }
3904 else if (Type->isEnumeralType()) {
3905 TD = Type->getAs<EnumType>()->getDecl();
3906 }
3907
3908 if (TD) {
3909 if (GlobalDefinedTags.count(TD))
3910 return;
3911
3912 bool IsNamedDefinition = false;
3913 if (IsTagDefinedInsideClass(IDecl, TD, IsNamedDefinition)) {
3914 RewriteObjCFieldDeclType(Type, Result);
3915 Result += ";";
3916 }
3917 if (IsNamedDefinition)
3918 GlobalDefinedTags.insert(TD);
3919 }
3920
3921}
3922
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00003923unsigned RewriteModernObjC::ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV) {
3924 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3925 if (ObjCInterefaceHasBitfieldGroups.count(CDecl)) {
3926 return IvarGroupNumber[IV];
3927 }
3928 unsigned GroupNo = 0;
3929 SmallVector<const ObjCIvarDecl *, 8> IVars;
3930 for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3931 IVD; IVD = IVD->getNextIvar())
3932 IVars.push_back(IVD);
3933
3934 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3935 if (IVars[i]->isBitField()) {
3936 IvarGroupNumber[IVars[i++]] = ++GroupNo;
3937 while (i < e && IVars[i]->isBitField())
3938 IvarGroupNumber[IVars[i++]] = GroupNo;
3939 if (i < e)
3940 --i;
3941 }
3942
3943 ObjCInterefaceHasBitfieldGroups.insert(CDecl);
3944 return IvarGroupNumber[IV];
3945}
3946
3947QualType RewriteModernObjC::SynthesizeBitfieldGroupStructType(
3948 ObjCIvarDecl *IV,
3949 SmallVectorImpl<ObjCIvarDecl *> &IVars) {
3950 std::string StructTagName;
3951 ObjCIvarBitfieldGroupType(IV, StructTagName);
3952 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct,
3953 Context->getTranslationUnitDecl(),
3954 SourceLocation(), SourceLocation(),
3955 &Context->Idents.get(StructTagName));
3956 for (unsigned i=0, e = IVars.size(); i < e; i++) {
3957 ObjCIvarDecl *Ivar = IVars[i];
3958 RD->addDecl(FieldDecl::Create(*Context, RD, SourceLocation(), SourceLocation(),
3959 &Context->Idents.get(Ivar->getName()),
3960 Ivar->getType(),
3961 0, /*Expr *BW */Ivar->getBitWidth(), false,
3962 ICIS_NoInit));
3963 }
3964 RD->completeDefinition();
3965 return Context->getTagDeclType(RD);
3966}
3967
3968QualType RewriteModernObjC::GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl *IV) {
3969 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3970 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3971 std::pair<const ObjCInterfaceDecl*, unsigned> tuple = std::make_pair(CDecl, GroupNo);
3972 if (GroupRecordType.count(tuple))
3973 return GroupRecordType[tuple];
3974
3975 SmallVector<ObjCIvarDecl *, 8> IVars;
3976 for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3977 IVD; IVD = IVD->getNextIvar()) {
3978 if (IVD->isBitField())
3979 IVars.push_back(const_cast<ObjCIvarDecl *>(IVD));
3980 else {
3981 if (!IVars.empty()) {
3982 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
3983 // Generate the struct type for this group of bitfield ivars.
3984 GroupRecordType[std::make_pair(CDecl, GroupNo)] =
3985 SynthesizeBitfieldGroupStructType(IVars[0], IVars);
3986 IVars.clear();
3987 }
3988 }
3989 }
3990 if (!IVars.empty()) {
3991 // Do the last one.
3992 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
3993 GroupRecordType[std::make_pair(CDecl, GroupNo)] =
3994 SynthesizeBitfieldGroupStructType(IVars[0], IVars);
3995 }
3996 QualType RetQT = GroupRecordType[tuple];
3997 assert(!RetQT.isNull() && "GetGroupRecordTypeForObjCIvarBitfield struct type is NULL");
3998
3999 return RetQT;
4000}
4001
4002/// ObjCIvarBitfieldGroupDecl - Names field decl. for ivar bitfield group.
4003/// Name would be: classname__GRBF_n where n is the group number for this ivar.
4004void RewriteModernObjC::ObjCIvarBitfieldGroupDecl(ObjCIvarDecl *IV,
4005 std::string &Result) {
4006 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
4007 Result += CDecl->getName();
4008 Result += "__GRBF_";
4009 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
4010 Result += utostr(GroupNo);
4011 return;
4012}
4013
4014/// ObjCIvarBitfieldGroupType - Names struct type for ivar bitfield group.
4015/// Name of the struct would be: classname__T_n where n is the group number for
4016/// this ivar.
4017void RewriteModernObjC::ObjCIvarBitfieldGroupType(ObjCIvarDecl *IV,
4018 std::string &Result) {
4019 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
4020 Result += CDecl->getName();
4021 Result += "__T_";
4022 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
4023 Result += utostr(GroupNo);
4024 return;
4025}
4026
4027/// ObjCIvarBitfieldGroupOffset - Names symbol for ivar bitfield group field offset.
4028/// Name would be: OBJC_IVAR_$_classname__GRBF_n where n is the group number for
4029/// this ivar.
4030void RewriteModernObjC::ObjCIvarBitfieldGroupOffset(ObjCIvarDecl *IV,
4031 std::string &Result) {
4032 Result += "OBJC_IVAR_$_";
4033 ObjCIvarBitfieldGroupDecl(IV, Result);
4034}
4035
4036#define SKIP_BITFIELDS(IX, ENDIX, VEC) { \
4037 while ((IX < ENDIX) && VEC[IX]->isBitField()) \
4038 ++IX; \
4039 if (IX < ENDIX) \
4040 --IX; \
4041}
4042
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004043/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
4044/// an objective-c class with ivars.
4045void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
4046 std::string &Result) {
4047 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
4048 assert(CDecl->getName() != "" &&
4049 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004050 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00004051 SmallVector<ObjCIvarDecl *, 8> IVars;
4052 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00004053 IVD; IVD = IVD->getNextIvar())
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00004054 IVars.push_back(IVD);
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00004055
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004056 SourceLocation LocStart = CDecl->getLocStart();
4057 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00004058
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004059 const char *startBuf = SM->getCharacterData(LocStart);
4060 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00004061
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004062 // If no ivars and no root or if its root, directly or indirectly,
4063 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00004064 if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) &&
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004065 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
4066 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
4067 ReplaceText(LocStart, endBuf-startBuf, Result);
4068 return;
4069 }
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00004070
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00004071 // Insert named struct/union definitions inside class to
4072 // outer scope. This follows semantics of locally defined
4073 // struct/unions in objective-c classes.
4074 for (unsigned i = 0, e = IVars.size(); i < e; i++)
4075 RewriteLocallyDefinedNamedAggregates(IVars[i], Result);
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00004076
4077 // Insert named structs which are syntheized to group ivar bitfields
4078 // to outer scope as well.
4079 for (unsigned i = 0, e = IVars.size(); i < e; i++)
4080 if (IVars[i]->isBitField()) {
4081 ObjCIvarDecl *IV = IVars[i];
4082 QualType QT = GetGroupRecordTypeForObjCIvarBitfield(IV);
4083 RewriteObjCFieldDeclType(QT, Result);
4084 Result += ";";
4085 // skip over ivar bitfields in this group.
4086 SKIP_BITFIELDS(i , e, IVars);
4087 }
4088
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004089 Result += "\nstruct ";
4090 Result += CDecl->getNameAsString();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00004091 Result += "_IMPL {\n";
4092
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00004093 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00004094 Result += "\tstruct "; Result += RCDecl->getNameAsString();
4095 Result += "_IMPL "; Result += RCDecl->getNameAsString();
4096 Result += "_IVARS;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004097 }
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00004098
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00004099 for (unsigned i = 0, e = IVars.size(); i < e; i++) {
4100 if (IVars[i]->isBitField()) {
4101 ObjCIvarDecl *IV = IVars[i];
4102 Result += "\tstruct ";
4103 ObjCIvarBitfieldGroupType(IV, Result); Result += " ";
4104 ObjCIvarBitfieldGroupDecl(IV, Result); Result += ";\n";
4105 // skip over ivar bitfields in this group.
4106 SKIP_BITFIELDS(i , e, IVars);
4107 }
4108 else
4109 RewriteObjCFieldDecl(IVars[i], Result);
4110 }
Fariborz Jahanian0b17b9a2012-02-12 21:36:23 +00004111
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00004112 Result += "};\n";
4113 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
4114 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00004115 // Mark this struct as having been generated.
4116 if (!ObjCSynthesizedStructs.insert(CDecl))
4117 llvm_unreachable("struct already synthesize- RewriteObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004118}
4119
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00004120/// RewriteIvarOffsetSymbols - Rewrite ivar offset symbols of those ivars which
4121/// have been referenced in an ivar access expression.
4122void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
4123 std::string &Result) {
4124 // write out ivar offset symbols which have been referenced in an ivar
4125 // access expression.
4126 llvm::SmallPtrSet<ObjCIvarDecl *, 8> Ivars = ReferencedIvars[CDecl];
4127 if (Ivars.empty())
4128 return;
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00004129
4130 llvm::DenseSet<std::pair<const ObjCInterfaceDecl*, unsigned> > GroupSymbolOutput;
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00004131 for (llvm::SmallPtrSet<ObjCIvarDecl *, 8>::iterator i = Ivars.begin(),
4132 e = Ivars.end(); i != e; i++) {
4133 ObjCIvarDecl *IvarDecl = (*i);
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00004134 const ObjCInterfaceDecl *IDecl = IvarDecl->getContainingInterface();
4135 unsigned GroupNo = 0;
4136 if (IvarDecl->isBitField()) {
4137 GroupNo = ObjCIvarBitfieldGroupNo(IvarDecl);
4138 if (GroupSymbolOutput.count(std::make_pair(IDecl, GroupNo)))
4139 continue;
4140 }
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00004141 Result += "\n";
4142 if (LangOpts.MicrosoftExt)
4143 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00004144 Result += "extern \"C\" ";
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00004145 if (LangOpts.MicrosoftExt &&
4146 IvarDecl->getAccessControl() != ObjCIvarDecl::Private &&
Fariborz Jahanian297976d2012-03-29 17:51:09 +00004147 IvarDecl->getAccessControl() != ObjCIvarDecl::Package)
4148 Result += "__declspec(dllimport) ";
4149
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00004150 Result += "unsigned long ";
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00004151 if (IvarDecl->isBitField()) {
4152 ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
4153 GroupSymbolOutput.insert(std::make_pair(IDecl, GroupNo));
4154 }
4155 else
4156 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00004157 Result += ";";
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00004158 }
4159}
4160
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004161//===----------------------------------------------------------------------===//
4162// Meta Data Emission
4163//===----------------------------------------------------------------------===//
4164
4165
4166/// RewriteImplementations - This routine rewrites all method implementations
4167/// and emits meta-data.
4168
4169void RewriteModernObjC::RewriteImplementations() {
4170 int ClsDefCount = ClassImplementation.size();
4171 int CatDefCount = CategoryImplementation.size();
4172
4173 // Rewrite implemented methods
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00004174 for (int i = 0; i < ClsDefCount; i++) {
4175 ObjCImplementationDecl *OIMP = ClassImplementation[i];
4176 ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
4177 if (CDecl->isImplicitInterfaceDecl())
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00004178 assert(false &&
4179 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00004180 RewriteImplementationDecl(OIMP);
4181 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004182
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00004183 for (int i = 0; i < CatDefCount; i++) {
4184 ObjCCategoryImplDecl *CIMP = CategoryImplementation[i];
4185 ObjCInterfaceDecl *CDecl = CIMP->getClassInterface();
4186 if (CDecl->isImplicitInterfaceDecl())
4187 assert(false &&
4188 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00004189 RewriteImplementationDecl(CIMP);
4190 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004191}
4192
4193void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
4194 const std::string &Name,
4195 ValueDecl *VD, bool def) {
4196 assert(BlockByRefDeclNo.count(VD) &&
4197 "RewriteByRefString: ByRef decl missing");
4198 if (def)
4199 ResultStr += "struct ";
4200 ResultStr += "__Block_byref_" + Name +
4201 "_" + utostr(BlockByRefDeclNo[VD]) ;
4202}
4203
4204static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
4205 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4206 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
4207 return false;
4208}
4209
4210std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
4211 StringRef funcName,
4212 std::string Tag) {
4213 const FunctionType *AFT = CE->getFunctionType();
4214 QualType RT = AFT->getResultType();
4215 std::string StructRef = "struct " + Tag;
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00004216 SourceLocation BlockLoc = CE->getExprLoc();
4217 std::string S;
4218 ConvertSourceLocationToLineDirective(BlockLoc, S);
4219
4220 S += "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
4221 funcName.str() + "_block_func_" + utostr(i);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004222
4223 BlockDecl *BD = CE->getBlockDecl();
4224
4225 if (isa<FunctionNoProtoType>(AFT)) {
4226 // No user-supplied arguments. Still need to pass in a pointer to the
4227 // block (to reference imported block decl refs).
4228 S += "(" + StructRef + " *__cself)";
4229 } else if (BD->param_empty()) {
4230 S += "(" + StructRef + " *__cself)";
4231 } else {
4232 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
4233 assert(FT && "SynthesizeBlockFunc: No function proto");
4234 S += '(';
4235 // first add the implicit argument.
4236 S += StructRef + " *__cself, ";
4237 std::string ParamStr;
4238 for (BlockDecl::param_iterator AI = BD->param_begin(),
4239 E = BD->param_end(); AI != E; ++AI) {
4240 if (AI != BD->param_begin()) S += ", ";
4241 ParamStr = (*AI)->getNameAsString();
4242 QualType QT = (*AI)->getType();
Fariborz Jahanian2610f902012-03-27 16:42:20 +00004243 (void)convertBlockPointerToFunctionPointer(QT);
4244 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004245 S += ParamStr;
4246 }
4247 if (FT->isVariadic()) {
4248 if (!BD->param_empty()) S += ", ";
4249 S += "...";
4250 }
4251 S += ')';
4252 }
4253 S += " {\n";
4254
4255 // Create local declarations to avoid rewriting all closure decl ref exprs.
4256 // First, emit a declaration for all "by ref" decls.
Craig Topper09d19ef2013-07-04 03:08:24 +00004257 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004258 E = BlockByRefDecls.end(); I != E; ++I) {
4259 S += " ";
4260 std::string Name = (*I)->getNameAsString();
4261 std::string TypeString;
4262 RewriteByRefString(TypeString, Name, (*I));
4263 TypeString += " *";
4264 Name = TypeString + Name;
4265 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
4266 }
4267 // Next, emit a declaration for all "by copy" declarations.
Craig Topper09d19ef2013-07-04 03:08:24 +00004268 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004269 E = BlockByCopyDecls.end(); I != E; ++I) {
4270 S += " ";
4271 // Handle nested closure invocation. For example:
4272 //
4273 // void (^myImportedClosure)(void);
4274 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
4275 //
4276 // void (^anotherClosure)(void);
4277 // anotherClosure = ^(void) {
4278 // myImportedClosure(); // import and invoke the closure
4279 // };
4280 //
4281 if (isTopLevelBlockPointerType((*I)->getType())) {
4282 RewriteBlockPointerTypeVariable(S, (*I));
4283 S += " = (";
4284 RewriteBlockPointerType(S, (*I)->getType());
4285 S += ")";
4286 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4287 }
4288 else {
4289 std::string Name = (*I)->getNameAsString();
4290 QualType QT = (*I)->getType();
4291 if (HasLocalVariableExternalStorage(*I))
4292 QT = Context->getPointerType(QT);
4293 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
4294 S += Name + " = __cself->" +
4295 (*I)->getNameAsString() + "; // bound by copy\n";
4296 }
4297 }
4298 std::string RewrittenStr = RewrittenBlockExprs[CE];
4299 const char *cstr = RewrittenStr.c_str();
4300 while (*cstr++ != '{') ;
4301 S += cstr;
4302 S += "\n";
4303 return S;
4304}
4305
4306std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
4307 StringRef funcName,
4308 std::string Tag) {
4309 std::string StructRef = "struct " + Tag;
4310 std::string S = "static void __";
4311
4312 S += funcName;
4313 S += "_block_copy_" + utostr(i);
4314 S += "(" + StructRef;
4315 S += "*dst, " + StructRef;
4316 S += "*src) {";
4317 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
4318 E = ImportedBlockDecls.end(); I != E; ++I) {
4319 ValueDecl *VD = (*I);
4320 S += "_Block_object_assign((void*)&dst->";
4321 S += (*I)->getNameAsString();
4322 S += ", (void*)src->";
4323 S += (*I)->getNameAsString();
4324 if (BlockByRefDeclsPtrSet.count((*I)))
4325 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4326 else if (VD->getType()->isBlockPointerType())
4327 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4328 else
4329 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4330 }
4331 S += "}\n";
4332
4333 S += "\nstatic void __";
4334 S += funcName;
4335 S += "_block_dispose_" + utostr(i);
4336 S += "(" + StructRef;
4337 S += "*src) {";
4338 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
4339 E = ImportedBlockDecls.end(); I != E; ++I) {
4340 ValueDecl *VD = (*I);
4341 S += "_Block_object_dispose((void*)src->";
4342 S += (*I)->getNameAsString();
4343 if (BlockByRefDeclsPtrSet.count((*I)))
4344 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4345 else if (VD->getType()->isBlockPointerType())
4346 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4347 else
4348 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4349 }
4350 S += "}\n";
4351 return S;
4352}
4353
4354std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4355 std::string Desc) {
4356 std::string S = "\nstruct " + Tag;
4357 std::string Constructor = " " + Tag;
4358
4359 S += " {\n struct __block_impl impl;\n";
4360 S += " struct " + Desc;
4361 S += "* Desc;\n";
4362
4363 Constructor += "(void *fp, "; // Invoke function pointer.
4364 Constructor += "struct " + Desc; // Descriptor pointer.
4365 Constructor += " *desc";
4366
4367 if (BlockDeclRefs.size()) {
4368 // Output all "by copy" declarations.
Craig Topper09d19ef2013-07-04 03:08:24 +00004369 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004370 E = BlockByCopyDecls.end(); I != E; ++I) {
4371 S += " ";
4372 std::string FieldName = (*I)->getNameAsString();
4373 std::string ArgName = "_" + FieldName;
4374 // Handle nested closure invocation. For example:
4375 //
4376 // void (^myImportedBlock)(void);
4377 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
4378 //
4379 // void (^anotherBlock)(void);
4380 // anotherBlock = ^(void) {
4381 // myImportedBlock(); // import and invoke the closure
4382 // };
4383 //
4384 if (isTopLevelBlockPointerType((*I)->getType())) {
4385 S += "struct __block_impl *";
4386 Constructor += ", void *" + ArgName;
4387 } else {
4388 QualType QT = (*I)->getType();
4389 if (HasLocalVariableExternalStorage(*I))
4390 QT = Context->getPointerType(QT);
4391 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
4392 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
4393 Constructor += ", " + ArgName;
4394 }
4395 S += FieldName + ";\n";
4396 }
4397 // Output all "by ref" declarations.
Craig Topper09d19ef2013-07-04 03:08:24 +00004398 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004399 E = BlockByRefDecls.end(); I != E; ++I) {
4400 S += " ";
4401 std::string FieldName = (*I)->getNameAsString();
4402 std::string ArgName = "_" + FieldName;
4403 {
4404 std::string TypeString;
4405 RewriteByRefString(TypeString, FieldName, (*I));
4406 TypeString += " *";
4407 FieldName = TypeString + FieldName;
4408 ArgName = TypeString + ArgName;
4409 Constructor += ", " + ArgName;
4410 }
4411 S += FieldName + "; // by ref\n";
4412 }
4413 // Finish writing the constructor.
4414 Constructor += ", int flags=0)";
4415 // Initialize all "by copy" arguments.
4416 bool firsTime = true;
Craig Topper09d19ef2013-07-04 03:08:24 +00004417 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004418 E = BlockByCopyDecls.end(); I != E; ++I) {
4419 std::string Name = (*I)->getNameAsString();
4420 if (firsTime) {
4421 Constructor += " : ";
4422 firsTime = false;
4423 }
4424 else
4425 Constructor += ", ";
4426 if (isTopLevelBlockPointerType((*I)->getType()))
4427 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4428 else
4429 Constructor += Name + "(_" + Name + ")";
4430 }
4431 // Initialize all "by ref" arguments.
Craig Topper09d19ef2013-07-04 03:08:24 +00004432 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004433 E = BlockByRefDecls.end(); I != E; ++I) {
4434 std::string Name = (*I)->getNameAsString();
4435 if (firsTime) {
4436 Constructor += " : ";
4437 firsTime = false;
4438 }
4439 else
4440 Constructor += ", ";
4441 Constructor += Name + "(_" + Name + "->__forwarding)";
4442 }
4443
4444 Constructor += " {\n";
4445 if (GlobalVarDecl)
4446 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4447 else
4448 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4449 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4450
4451 Constructor += " Desc = desc;\n";
4452 } else {
4453 // Finish writing the constructor.
4454 Constructor += ", int flags=0) {\n";
4455 if (GlobalVarDecl)
4456 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4457 else
4458 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4459 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4460 Constructor += " Desc = desc;\n";
4461 }
4462 Constructor += " ";
4463 Constructor += "}\n";
4464 S += Constructor;
4465 S += "};\n";
4466 return S;
4467}
4468
4469std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag,
4470 std::string ImplTag, int i,
4471 StringRef FunName,
4472 unsigned hasCopy) {
4473 std::string S = "\nstatic struct " + DescTag;
4474
Fariborz Jahanian8b08adb2012-05-03 21:44:12 +00004475 S += " {\n size_t reserved;\n";
4476 S += " size_t Block_size;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004477 if (hasCopy) {
4478 S += " void (*copy)(struct ";
4479 S += ImplTag; S += "*, struct ";
4480 S += ImplTag; S += "*);\n";
4481
4482 S += " void (*dispose)(struct ";
4483 S += ImplTag; S += "*);\n";
4484 }
4485 S += "} ";
4486
4487 S += DescTag + "_DATA = { 0, sizeof(struct ";
4488 S += ImplTag + ")";
4489 if (hasCopy) {
4490 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4491 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
4492 }
4493 S += "};\n";
4494 return S;
4495}
4496
4497void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
4498 StringRef FunName) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004499 bool RewriteSC = (GlobalVarDecl &&
4500 !Blocks.empty() &&
4501 GlobalVarDecl->getStorageClass() == SC_Static &&
4502 GlobalVarDecl->getType().getCVRQualifiers());
4503 if (RewriteSC) {
4504 std::string SC(" void __");
4505 SC += GlobalVarDecl->getNameAsString();
4506 SC += "() {}";
4507 InsertText(FunLocStart, SC);
4508 }
4509
4510 // Insert closures that were part of the function.
4511 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4512 CollectBlockDeclRefInfo(Blocks[i]);
4513 // Need to copy-in the inner copied-in variables not actually used in this
4514 // block.
4515 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
John McCallf4b88a42012-03-10 09:33:50 +00004516 DeclRefExpr *Exp = InnerDeclRefs[count++];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004517 ValueDecl *VD = Exp->getDecl();
4518 BlockDeclRefs.push_back(Exp);
John McCallf4b88a42012-03-10 09:33:50 +00004519 if (!VD->hasAttr<BlocksAttr>()) {
4520 if (!BlockByCopyDeclsPtrSet.count(VD)) {
4521 BlockByCopyDeclsPtrSet.insert(VD);
4522 BlockByCopyDecls.push_back(VD);
4523 }
4524 continue;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004525 }
John McCallf4b88a42012-03-10 09:33:50 +00004526
4527 if (!BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004528 BlockByRefDeclsPtrSet.insert(VD);
4529 BlockByRefDecls.push_back(VD);
4530 }
John McCallf4b88a42012-03-10 09:33:50 +00004531
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004532 // imported objects in the inner blocks not used in the outer
4533 // blocks must be copied/disposed in the outer block as well.
John McCallf4b88a42012-03-10 09:33:50 +00004534 if (VD->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004535 VD->getType()->isBlockPointerType())
4536 ImportedBlockDecls.insert(VD);
4537 }
4538
4539 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4540 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
4541
4542 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
4543
4544 InsertText(FunLocStart, CI);
4545
4546 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
4547
4548 InsertText(FunLocStart, CF);
4549
4550 if (ImportedBlockDecls.size()) {
4551 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
4552 InsertText(FunLocStart, HF);
4553 }
4554 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4555 ImportedBlockDecls.size() > 0);
4556 InsertText(FunLocStart, BD);
4557
4558 BlockDeclRefs.clear();
4559 BlockByRefDecls.clear();
4560 BlockByRefDeclsPtrSet.clear();
4561 BlockByCopyDecls.clear();
4562 BlockByCopyDeclsPtrSet.clear();
4563 ImportedBlockDecls.clear();
4564 }
4565 if (RewriteSC) {
4566 // Must insert any 'const/volatile/static here. Since it has been
4567 // removed as result of rewriting of block literals.
4568 std::string SC;
4569 if (GlobalVarDecl->getStorageClass() == SC_Static)
4570 SC = "static ";
4571 if (GlobalVarDecl->getType().isConstQualified())
4572 SC += "const ";
4573 if (GlobalVarDecl->getType().isVolatileQualified())
4574 SC += "volatile ";
4575 if (GlobalVarDecl->getType().isRestrictQualified())
4576 SC += "restrict ";
4577 InsertText(FunLocStart, SC);
4578 }
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004579 if (GlobalConstructionExp) {
4580 // extra fancy dance for global literal expression.
4581
4582 // Always the latest block expression on the block stack.
4583 std::string Tag = "__";
4584 Tag += FunName;
4585 Tag += "_block_impl_";
4586 Tag += utostr(Blocks.size()-1);
4587 std::string globalBuf = "static ";
4588 globalBuf += Tag; globalBuf += " ";
4589 std::string SStr;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004590
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004591 llvm::raw_string_ostream constructorExprBuf(SStr);
Richard Smithd1420c62012-08-16 03:56:14 +00004592 GlobalConstructionExp->printPretty(constructorExprBuf, 0,
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004593 PrintingPolicy(LangOpts));
4594 globalBuf += constructorExprBuf.str();
4595 globalBuf += ";\n";
4596 InsertText(FunLocStart, globalBuf);
4597 GlobalConstructionExp = 0;
4598 }
4599
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004600 Blocks.clear();
4601 InnerDeclRefsCount.clear();
4602 InnerDeclRefs.clear();
4603 RewrittenBlockExprs.clear();
4604}
4605
4606void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
Fariborz Jahanian04189532012-04-25 17:56:48 +00004607 SourceLocation FunLocStart =
4608 (!Blocks.empty()) ? getFunctionSourceLocation(*this, FD)
4609 : FD->getTypeSpecStartLoc();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004610 StringRef FuncName = FD->getName();
4611
4612 SynthesizeBlockLiterals(FunLocStart, FuncName);
4613}
4614
4615static void BuildUniqueMethodName(std::string &Name,
4616 ObjCMethodDecl *MD) {
4617 ObjCInterfaceDecl *IFace = MD->getClassInterface();
4618 Name = IFace->getName();
4619 Name += "__" + MD->getSelector().getAsString();
4620 // Convert colons to underscores.
4621 std::string::size_type loc = 0;
4622 while ((loc = Name.find(":", loc)) != std::string::npos)
4623 Name.replace(loc, 1, "_");
4624}
4625
4626void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
4627 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4628 //SourceLocation FunLocStart = MD->getLocStart();
4629 SourceLocation FunLocStart = MD->getLocStart();
4630 std::string FuncName;
4631 BuildUniqueMethodName(FuncName, MD);
4632 SynthesizeBlockLiterals(FunLocStart, FuncName);
4633}
4634
4635void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
4636 for (Stmt::child_range CI = S->children(); CI; ++CI)
4637 if (*CI) {
4638 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4639 GetBlockDeclRefExprs(CBE->getBody());
4640 else
4641 GetBlockDeclRefExprs(*CI);
4642 }
4643 // Handle specific things.
Fariborz Jahanian0e976812012-04-16 23:00:57 +00004644 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4645 if (DRE->refersToEnclosingLocal()) {
4646 // FIXME: Handle enums.
4647 if (!isa<FunctionDecl>(DRE->getDecl()))
4648 BlockDeclRefs.push_back(DRE);
4649 if (HasLocalVariableExternalStorage(DRE->getDecl()))
4650 BlockDeclRefs.push_back(DRE);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004651 }
Fariborz Jahanian0e976812012-04-16 23:00:57 +00004652 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004653
4654 return;
4655}
4656
Craig Topper6b9240e2013-07-05 19:34:19 +00004657void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
4658 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004659 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
4660 for (Stmt::child_range CI = S->children(); CI; ++CI)
4661 if (*CI) {
4662 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
4663 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
4664 GetInnerBlockDeclRefExprs(CBE->getBody(),
4665 InnerBlockDeclRefs,
4666 InnerContexts);
4667 }
4668 else
4669 GetInnerBlockDeclRefExprs(*CI,
4670 InnerBlockDeclRefs,
4671 InnerContexts);
4672
4673 }
4674 // Handle specific things.
John McCallf4b88a42012-03-10 09:33:50 +00004675 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4676 if (DRE->refersToEnclosingLocal()) {
4677 if (!isa<FunctionDecl>(DRE->getDecl()) &&
4678 !InnerContexts.count(DRE->getDecl()->getDeclContext()))
4679 InnerBlockDeclRefs.push_back(DRE);
4680 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
4681 if (Var->isFunctionOrMethodVarDecl())
4682 ImportedLocalExternalDecls.insert(Var);
4683 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004684 }
4685
4686 return;
4687}
4688
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004689/// convertObjCTypeToCStyleType - This routine converts such objc types
4690/// as qualified objects, and blocks to their closest c/c++ types that
4691/// it can. It returns true if input type was modified.
4692bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
4693 QualType oldT = T;
4694 convertBlockPointerToFunctionPointer(T);
4695 if (T->isFunctionPointerType()) {
4696 QualType PointeeTy;
4697 if (const PointerType* PT = T->getAs<PointerType>()) {
4698 PointeeTy = PT->getPointeeType();
4699 if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
4700 T = convertFunctionTypeOfBlocks(FT);
4701 T = Context->getPointerType(T);
4702 }
4703 }
4704 }
4705
4706 convertToUnqualifiedObjCType(T);
4707 return T != oldT;
4708}
4709
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004710/// convertFunctionTypeOfBlocks - This routine converts a function type
4711/// whose result type may be a block pointer or whose argument type(s)
4712/// might be block pointers to an equivalent function type replacing
4713/// all block pointers to function pointers.
4714QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4715 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4716 // FTP will be null for closures that don't take arguments.
4717 // Generate a funky cast.
4718 SmallVector<QualType, 8> ArgTypes;
4719 QualType Res = FT->getResultType();
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004720 bool modified = convertObjCTypeToCStyleType(Res);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004721
4722 if (FTP) {
4723 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4724 E = FTP->arg_type_end(); I && (I != E); ++I) {
4725 QualType t = *I;
4726 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004727 if (convertObjCTypeToCStyleType(t))
4728 modified = true;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004729 ArgTypes.push_back(t);
4730 }
4731 }
4732 QualType FuncType;
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004733 if (modified)
Jordan Rosebea522f2013-03-08 21:51:21 +00004734 FuncType = getSimpleFunctionType(Res, ArgTypes);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004735 else FuncType = QualType(FT, 0);
4736 return FuncType;
4737}
4738
4739Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
4740 // Navigate to relevant type information.
4741 const BlockPointerType *CPT = 0;
4742
4743 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
4744 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004745 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
4746 CPT = MExpr->getType()->getAs<BlockPointerType>();
4747 }
4748 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4749 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4750 }
4751 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4752 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4753 else if (const ConditionalOperator *CEXPR =
4754 dyn_cast<ConditionalOperator>(BlockExp)) {
4755 Expr *LHSExp = CEXPR->getLHS();
4756 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4757 Expr *RHSExp = CEXPR->getRHS();
4758 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4759 Expr *CONDExp = CEXPR->getCond();
4760 ConditionalOperator *CondExpr =
4761 new (Context) ConditionalOperator(CONDExp,
4762 SourceLocation(), cast<Expr>(LHSStmt),
4763 SourceLocation(), cast<Expr>(RHSStmt),
4764 Exp->getType(), VK_RValue, OK_Ordinary);
4765 return CondExpr;
4766 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4767 CPT = IRE->getType()->getAs<BlockPointerType>();
4768 } else if (const PseudoObjectExpr *POE
4769 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
4770 CPT = POE->getType()->castAs<BlockPointerType>();
4771 } else {
4772 assert(1 && "RewriteBlockClass: Bad type");
4773 }
4774 assert(CPT && "RewriteBlockClass: Bad type");
4775 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
4776 assert(FT && "RewriteBlockClass: Bad type");
4777 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4778 // FTP will be null for closures that don't take arguments.
4779
4780 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4781 SourceLocation(), SourceLocation(),
4782 &Context->Idents.get("__block_impl"));
4783 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
4784
4785 // Generate a funky cast.
4786 SmallVector<QualType, 8> ArgTypes;
4787
4788 // Push the block argument type.
4789 ArgTypes.push_back(PtrBlock);
4790 if (FTP) {
4791 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4792 E = FTP->arg_type_end(); I && (I != E); ++I) {
4793 QualType t = *I;
4794 // Make sure we convert "t (^)(...)" to "t (*)(...)".
4795 if (!convertBlockPointerToFunctionPointer(t))
4796 convertToUnqualifiedObjCType(t);
4797 ArgTypes.push_back(t);
4798 }
4799 }
4800 // Now do the pointer to function cast.
Jordan Rosebea522f2013-03-08 21:51:21 +00004801 QualType PtrToFuncCastType = getSimpleFunctionType(Exp->getType(), ArgTypes);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004802
4803 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
4804
4805 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4806 CK_BitCast,
4807 const_cast<Expr*>(BlockExp));
4808 // Don't forget the parens to enforce the proper binding.
4809 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4810 BlkCast);
4811 //PE->dump();
4812
4813 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4814 SourceLocation(),
4815 &Context->Idents.get("FuncPtr"),
4816 Context->VoidPtrTy, 0,
4817 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00004818 ICIS_NoInit);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004819 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4820 FD->getType(), VK_LValue,
4821 OK_Ordinary);
4822
4823
4824 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4825 CK_BitCast, ME);
4826 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
4827
4828 SmallVector<Expr*, 8> BlkExprs;
4829 // Add the implicit argument.
4830 BlkExprs.push_back(BlkCast);
4831 // Add the user arguments.
4832 for (CallExpr::arg_iterator I = Exp->arg_begin(),
4833 E = Exp->arg_end(); I != E; ++I) {
4834 BlkExprs.push_back(*I);
4835 }
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004836 CallExpr *CE = new (Context) CallExpr(*Context, PE, BlkExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004837 Exp->getType(), VK_RValue,
4838 SourceLocation());
4839 return CE;
4840}
4841
4842// We need to return the rewritten expression to handle cases where the
John McCallf4b88a42012-03-10 09:33:50 +00004843// DeclRefExpr is embedded in another expression being rewritten.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004844// For example:
4845//
4846// int main() {
4847// __block Foo *f;
4848// __block int i;
4849//
4850// void (^myblock)() = ^() {
John McCallf4b88a42012-03-10 09:33:50 +00004851// [f test]; // f is a DeclRefExpr embedded in a message (which is being rewritten).
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004852// i = 77;
4853// };
4854//}
John McCallf4b88a42012-03-10 09:33:50 +00004855Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004856 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
4857 // for each DeclRefExp where BYREFVAR is name of the variable.
John McCallf4b88a42012-03-10 09:33:50 +00004858 ValueDecl *VD = DeclRefExp->getDecl();
4859 bool isArrow = DeclRefExp->refersToEnclosingLocal();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004860
4861 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4862 SourceLocation(),
4863 &Context->Idents.get("__forwarding"),
4864 Context->VoidPtrTy, 0,
4865 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00004866 ICIS_NoInit);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004867 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4868 FD, SourceLocation(),
4869 FD->getType(), VK_LValue,
4870 OK_Ordinary);
4871
4872 StringRef Name = VD->getName();
4873 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
4874 &Context->Idents.get(Name),
4875 Context->VoidPtrTy, 0,
4876 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00004877 ICIS_NoInit);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004878 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
4879 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
4880
4881
4882
4883 // Need parens to enforce precedence.
4884 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
4885 DeclRefExp->getExprLoc(),
4886 ME);
4887 ReplaceStmt(DeclRefExp, PE);
4888 return PE;
4889}
4890
4891// Rewrites the imported local variable V with external storage
4892// (static, extern, etc.) as *V
4893//
4894Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4895 ValueDecl *VD = DRE->getDecl();
4896 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4897 if (!ImportedLocalExternalDecls.count(Var))
4898 return DRE;
4899 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4900 VK_LValue, OK_Ordinary,
4901 DRE->getLocation());
4902 // Need parens to enforce precedence.
4903 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4904 Exp);
4905 ReplaceStmt(DRE, PE);
4906 return PE;
4907}
4908
4909void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4910 SourceLocation LocStart = CE->getLParenLoc();
4911 SourceLocation LocEnd = CE->getRParenLoc();
4912
4913 // Need to avoid trying to rewrite synthesized casts.
4914 if (LocStart.isInvalid())
4915 return;
4916 // Need to avoid trying to rewrite casts contained in macros.
4917 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4918 return;
4919
4920 const char *startBuf = SM->getCharacterData(LocStart);
4921 const char *endBuf = SM->getCharacterData(LocEnd);
4922 QualType QT = CE->getType();
4923 const Type* TypePtr = QT->getAs<Type>();
4924 if (isa<TypeOfExprType>(TypePtr)) {
4925 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4926 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4927 std::string TypeAsString = "(";
4928 RewriteBlockPointerType(TypeAsString, QT);
4929 TypeAsString += ")";
4930 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
4931 return;
4932 }
4933 // advance the location to startArgList.
4934 const char *argPtr = startBuf;
4935
4936 while (*argPtr++ && (argPtr < endBuf)) {
4937 switch (*argPtr) {
4938 case '^':
4939 // Replace the '^' with '*'.
4940 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
4941 ReplaceText(LocStart, 1, "*");
4942 break;
4943 }
4944 }
4945 return;
4946}
4947
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00004948void RewriteModernObjC::RewriteImplicitCastObjCExpr(CastExpr *IC) {
4949 CastKind CastKind = IC->getCastKind();
Fariborz Jahanian43aa1c32012-04-16 22:14:01 +00004950 if (CastKind != CK_BlockPointerToObjCPointerCast &&
4951 CastKind != CK_AnyPointerToBlockPointerCast)
4952 return;
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00004953
Fariborz Jahanian43aa1c32012-04-16 22:14:01 +00004954 QualType QT = IC->getType();
4955 (void)convertBlockPointerToFunctionPointer(QT);
4956 std::string TypeString(QT.getAsString(Context->getPrintingPolicy()));
4957 std::string Str = "(";
4958 Str += TypeString;
4959 Str += ")";
4960 InsertText(IC->getSubExpr()->getLocStart(), &Str[0], Str.size());
4961
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00004962 return;
4963}
4964
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004965void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4966 SourceLocation DeclLoc = FD->getLocation();
4967 unsigned parenCount = 0;
4968
4969 // We have 1 or more arguments that have closure pointers.
4970 const char *startBuf = SM->getCharacterData(DeclLoc);
4971 const char *startArgList = strchr(startBuf, '(');
4972
4973 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
4974
4975 parenCount++;
4976 // advance the location to startArgList.
4977 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
4978 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
4979
4980 const char *argPtr = startArgList;
4981
4982 while (*argPtr++ && parenCount) {
4983 switch (*argPtr) {
4984 case '^':
4985 // Replace the '^' with '*'.
4986 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
4987 ReplaceText(DeclLoc, 1, "*");
4988 break;
4989 case '(':
4990 parenCount++;
4991 break;
4992 case ')':
4993 parenCount--;
4994 break;
4995 }
4996 }
4997 return;
4998}
4999
5000bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
5001 const FunctionProtoType *FTP;
5002 const PointerType *PT = QT->getAs<PointerType>();
5003 if (PT) {
5004 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
5005 } else {
5006 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
5007 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
5008 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
5009 }
5010 if (FTP) {
5011 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
5012 E = FTP->arg_type_end(); I != E; ++I)
5013 if (isTopLevelBlockPointerType(*I))
5014 return true;
5015 }
5016 return false;
5017}
5018
5019bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
5020 const FunctionProtoType *FTP;
5021 const PointerType *PT = QT->getAs<PointerType>();
5022 if (PT) {
5023 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
5024 } else {
5025 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
5026 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
5027 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
5028 }
5029 if (FTP) {
5030 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
5031 E = FTP->arg_type_end(); I != E; ++I) {
5032 if ((*I)->isObjCQualifiedIdType())
5033 return true;
5034 if ((*I)->isObjCObjectPointerType() &&
5035 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
5036 return true;
5037 }
5038
5039 }
5040 return false;
5041}
5042
5043void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
5044 const char *&RParen) {
5045 const char *argPtr = strchr(Name, '(');
5046 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
5047
5048 LParen = argPtr; // output the start.
5049 argPtr++; // skip past the left paren.
5050 unsigned parenCount = 1;
5051
5052 while (*argPtr && parenCount) {
5053 switch (*argPtr) {
5054 case '(': parenCount++; break;
5055 case ')': parenCount--; break;
5056 default: break;
5057 }
5058 if (parenCount) argPtr++;
5059 }
5060 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
5061 RParen = argPtr; // output the end
5062}
5063
5064void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
5065 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
5066 RewriteBlockPointerFunctionArgs(FD);
5067 return;
5068 }
5069 // Handle Variables and Typedefs.
5070 SourceLocation DeclLoc = ND->getLocation();
5071 QualType DeclT;
5072 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
5073 DeclT = VD->getType();
5074 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
5075 DeclT = TDD->getUnderlyingType();
5076 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
5077 DeclT = FD->getType();
5078 else
5079 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
5080
5081 const char *startBuf = SM->getCharacterData(DeclLoc);
5082 const char *endBuf = startBuf;
5083 // scan backward (from the decl location) for the end of the previous decl.
5084 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
5085 startBuf--;
5086 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
5087 std::string buf;
5088 unsigned OrigLength=0;
5089 // *startBuf != '^' if we are dealing with a pointer to function that
5090 // may take block argument types (which will be handled below).
5091 if (*startBuf == '^') {
5092 // Replace the '^' with '*', computing a negative offset.
5093 buf = '*';
5094 startBuf++;
5095 OrigLength++;
5096 }
5097 while (*startBuf != ')') {
5098 buf += *startBuf;
5099 startBuf++;
5100 OrigLength++;
5101 }
5102 buf += ')';
5103 OrigLength++;
5104
5105 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
5106 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
5107 // Replace the '^' with '*' for arguments.
5108 // Replace id<P> with id/*<>*/
5109 DeclLoc = ND->getLocation();
5110 startBuf = SM->getCharacterData(DeclLoc);
5111 const char *argListBegin, *argListEnd;
5112 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
5113 while (argListBegin < argListEnd) {
5114 if (*argListBegin == '^')
5115 buf += '*';
5116 else if (*argListBegin == '<') {
5117 buf += "/*";
5118 buf += *argListBegin++;
Dmitri Gribenko1ad23d62012-09-10 21:20:09 +00005119 OrigLength++;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005120 while (*argListBegin != '>') {
5121 buf += *argListBegin++;
5122 OrigLength++;
5123 }
5124 buf += *argListBegin;
5125 buf += "*/";
5126 }
5127 else
5128 buf += *argListBegin;
5129 argListBegin++;
5130 OrigLength++;
5131 }
5132 buf += ')';
5133 OrigLength++;
5134 }
5135 ReplaceText(Start, OrigLength, buf);
5136
5137 return;
5138}
5139
5140
5141/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
5142/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
5143/// struct Block_byref_id_object *src) {
5144/// _Block_object_assign (&_dest->object, _src->object,
5145/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5146/// [|BLOCK_FIELD_IS_WEAK]) // object
5147/// _Block_object_assign(&_dest->object, _src->object,
5148/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5149/// [|BLOCK_FIELD_IS_WEAK]) // block
5150/// }
5151/// And:
5152/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
5153/// _Block_object_dispose(_src->object,
5154/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5155/// [|BLOCK_FIELD_IS_WEAK]) // object
5156/// _Block_object_dispose(_src->object,
5157/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5158/// [|BLOCK_FIELD_IS_WEAK]) // block
5159/// }
5160
5161std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
5162 int flag) {
5163 std::string S;
5164 if (CopyDestroyCache.count(flag))
5165 return S;
5166 CopyDestroyCache.insert(flag);
5167 S = "static void __Block_byref_id_object_copy_";
5168 S += utostr(flag);
5169 S += "(void *dst, void *src) {\n";
5170
5171 // offset into the object pointer is computed as:
5172 // void * + void* + int + int + void* + void *
5173 unsigned IntSize =
5174 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5175 unsigned VoidPtrSize =
5176 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
5177
5178 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
5179 S += " _Block_object_assign((char*)dst + ";
5180 S += utostr(offset);
5181 S += ", *(void * *) ((char*)src + ";
5182 S += utostr(offset);
5183 S += "), ";
5184 S += utostr(flag);
5185 S += ");\n}\n";
5186
5187 S += "static void __Block_byref_id_object_dispose_";
5188 S += utostr(flag);
5189 S += "(void *src) {\n";
5190 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
5191 S += utostr(offset);
5192 S += "), ";
5193 S += utostr(flag);
5194 S += ");\n}\n";
5195 return S;
5196}
5197
5198/// RewriteByRefVar - For each __block typex ND variable this routine transforms
5199/// the declaration into:
5200/// struct __Block_byref_ND {
5201/// void *__isa; // NULL for everything except __weak pointers
5202/// struct __Block_byref_ND *__forwarding;
5203/// int32_t __flags;
5204/// int32_t __size;
5205/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
5206/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
5207/// typex ND;
5208/// };
5209///
5210/// It then replaces declaration of ND variable with:
5211/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
5212/// __size=sizeof(struct __Block_byref_ND),
5213/// ND=initializer-if-any};
5214///
5215///
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00005216void RewriteModernObjC::RewriteByRefVar(VarDecl *ND, bool firstDecl,
5217 bool lastDecl) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005218 int flag = 0;
5219 int isa = 0;
5220 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
5221 if (DeclLoc.isInvalid())
5222 // If type location is missing, it is because of missing type (a warning).
5223 // Use variable's location which is good for this case.
5224 DeclLoc = ND->getLocation();
5225 const char *startBuf = SM->getCharacterData(DeclLoc);
5226 SourceLocation X = ND->getLocEnd();
5227 X = SM->getExpansionLoc(X);
5228 const char *endBuf = SM->getCharacterData(X);
5229 std::string Name(ND->getNameAsString());
5230 std::string ByrefType;
5231 RewriteByRefString(ByrefType, Name, ND, true);
5232 ByrefType += " {\n";
5233 ByrefType += " void *__isa;\n";
5234 RewriteByRefString(ByrefType, Name, ND);
5235 ByrefType += " *__forwarding;\n";
5236 ByrefType += " int __flags;\n";
5237 ByrefType += " int __size;\n";
5238 // Add void *__Block_byref_id_object_copy;
5239 // void *__Block_byref_id_object_dispose; if needed.
5240 QualType Ty = ND->getType();
Fariborz Jahanianb15c8982012-11-28 23:12:17 +00005241 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty, ND);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005242 if (HasCopyAndDispose) {
5243 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
5244 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
5245 }
5246
5247 QualType T = Ty;
5248 (void)convertBlockPointerToFunctionPointer(T);
5249 T.getAsStringInternal(Name, Context->getPrintingPolicy());
5250
5251 ByrefType += " " + Name + ";\n";
5252 ByrefType += "};\n";
5253 // Insert this type in global scope. It is needed by helper function.
5254 SourceLocation FunLocStart;
5255 if (CurFunctionDef)
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00005256 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005257 else {
5258 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
5259 FunLocStart = CurMethodDef->getLocStart();
5260 }
5261 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian8247c4e2012-04-24 16:45:27 +00005262
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005263 if (Ty.isObjCGCWeak()) {
5264 flag |= BLOCK_FIELD_IS_WEAK;
5265 isa = 1;
5266 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005267 if (HasCopyAndDispose) {
5268 flag = BLOCK_BYREF_CALLER;
5269 QualType Ty = ND->getType();
5270 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
5271 if (Ty->isBlockPointerType())
5272 flag |= BLOCK_FIELD_IS_BLOCK;
5273 else
5274 flag |= BLOCK_FIELD_IS_OBJECT;
5275 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
5276 if (!HF.empty())
Fariborz Jahanian31c4a4b2013-02-07 22:50:40 +00005277 Preamble += HF;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005278 }
5279
5280 // struct __Block_byref_ND ND =
5281 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
5282 // initializer-if-any};
5283 bool hasInit = (ND->getInit() != 0);
Fariborz Jahanian104dbf92012-04-11 23:57:12 +00005284 // FIXME. rewriter does not support __block c++ objects which
5285 // require construction.
Fariborz Jahanian65a7c682012-04-26 23:20:25 +00005286 if (hasInit)
5287 if (CXXConstructExpr *CExp = dyn_cast<CXXConstructExpr>(ND->getInit())) {
5288 CXXConstructorDecl *CXXDecl = CExp->getConstructor();
5289 if (CXXDecl && CXXDecl->isDefaultConstructor())
5290 hasInit = false;
5291 }
5292
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005293 unsigned flags = 0;
5294 if (HasCopyAndDispose)
5295 flags |= BLOCK_HAS_COPY_DISPOSE;
5296 Name = ND->getNameAsString();
5297 ByrefType.clear();
5298 RewriteByRefString(ByrefType, Name, ND);
5299 std::string ForwardingCastType("(");
5300 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian8247c4e2012-04-24 16:45:27 +00005301 ByrefType += " " + Name + " = {(void*)";
5302 ByrefType += utostr(isa);
5303 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
5304 ByrefType += utostr(flags);
5305 ByrefType += ", ";
5306 ByrefType += "sizeof(";
5307 RewriteByRefString(ByrefType, Name, ND);
5308 ByrefType += ")";
5309 if (HasCopyAndDispose) {
5310 ByrefType += ", __Block_byref_id_object_copy_";
5311 ByrefType += utostr(flag);
5312 ByrefType += ", __Block_byref_id_object_dispose_";
5313 ByrefType += utostr(flag);
5314 }
5315
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00005316 if (!firstDecl) {
5317 // In multiple __block declarations, and for all but 1st declaration,
5318 // find location of the separating comma. This would be start location
5319 // where new text is to be inserted.
5320 DeclLoc = ND->getLocation();
5321 const char *startDeclBuf = SM->getCharacterData(DeclLoc);
5322 const char *commaBuf = startDeclBuf;
5323 while (*commaBuf != ',')
5324 commaBuf--;
5325 assert((*commaBuf == ',') && "RewriteByRefVar: can't find ','");
5326 DeclLoc = DeclLoc.getLocWithOffset(commaBuf - startDeclBuf);
5327 startBuf = commaBuf;
5328 }
5329
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005330 if (!hasInit) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005331 ByrefType += "};\n";
5332 unsigned nameSize = Name.size();
5333 // for block or function pointer declaration. Name is aleady
5334 // part of the declaration.
5335 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
5336 nameSize = 1;
5337 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
5338 }
5339 else {
Fariborz Jahanian8247c4e2012-04-24 16:45:27 +00005340 ByrefType += ", ";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005341 SourceLocation startLoc;
5342 Expr *E = ND->getInit();
5343 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5344 startLoc = ECE->getLParenLoc();
5345 else
5346 startLoc = E->getLocStart();
5347 startLoc = SM->getExpansionLoc(startLoc);
5348 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005349 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005350
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00005351 const char separator = lastDecl ? ';' : ',';
5352 const char *startInitializerBuf = SM->getCharacterData(startLoc);
5353 const char *separatorBuf = strchr(startInitializerBuf, separator);
5354 assert((*separatorBuf == separator) &&
5355 "RewriteByRefVar: can't find ';' or ','");
5356 SourceLocation separatorLoc =
5357 startLoc.getLocWithOffset(separatorBuf-startInitializerBuf);
5358
5359 InsertText(separatorLoc, lastDecl ? "}" : "};\n");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005360 }
5361 return;
5362}
5363
5364void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
5365 // Add initializers for any closure decl refs.
5366 GetBlockDeclRefExprs(Exp->getBody());
5367 if (BlockDeclRefs.size()) {
5368 // Unique all "by copy" declarations.
5369 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00005370 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005371 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5372 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5373 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5374 }
5375 }
5376 // Unique all "by ref" declarations.
5377 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00005378 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005379 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5380 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5381 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5382 }
5383 }
5384 // Find any imported blocks...they will need special attention.
5385 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00005386 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005387 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5388 BlockDeclRefs[i]->getType()->isBlockPointerType())
5389 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
5390 }
5391}
5392
5393FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) {
5394 IdentifierInfo *ID = &Context->Idents.get(name);
5395 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
5396 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
5397 SourceLocation(), ID, FType, 0, SC_Extern,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00005398 false, false);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005399}
5400
5401Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp,
Craig Topper6b9240e2013-07-05 19:34:19 +00005402 const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs) {
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +00005403
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005404 const BlockDecl *block = Exp->getBlockDecl();
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +00005405
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005406 Blocks.push_back(Exp);
5407
5408 CollectBlockDeclRefInfo(Exp);
5409
5410 // Add inner imported variables now used in current block.
5411 int countOfInnerDecls = 0;
5412 if (!InnerBlockDeclRefs.empty()) {
5413 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
John McCallf4b88a42012-03-10 09:33:50 +00005414 DeclRefExpr *Exp = InnerBlockDeclRefs[i];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005415 ValueDecl *VD = Exp->getDecl();
John McCallf4b88a42012-03-10 09:33:50 +00005416 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005417 // We need to save the copied-in variables in nested
5418 // blocks because it is needed at the end for some of the API generations.
5419 // See SynthesizeBlockLiterals routine.
5420 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5421 BlockDeclRefs.push_back(Exp);
5422 BlockByCopyDeclsPtrSet.insert(VD);
5423 BlockByCopyDecls.push_back(VD);
5424 }
John McCallf4b88a42012-03-10 09:33:50 +00005425 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005426 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5427 BlockDeclRefs.push_back(Exp);
5428 BlockByRefDeclsPtrSet.insert(VD);
5429 BlockByRefDecls.push_back(VD);
5430 }
5431 }
5432 // Find any imported blocks...they will need special attention.
5433 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00005434 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005435 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5436 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5437 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
5438 }
5439 InnerDeclRefsCount.push_back(countOfInnerDecls);
5440
5441 std::string FuncName;
5442
5443 if (CurFunctionDef)
5444 FuncName = CurFunctionDef->getNameAsString();
5445 else if (CurMethodDef)
5446 BuildUniqueMethodName(FuncName, CurMethodDef);
5447 else if (GlobalVarDecl)
5448 FuncName = std::string(GlobalVarDecl->getNameAsString());
5449
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00005450 bool GlobalBlockExpr =
5451 block->getDeclContext()->getRedeclContext()->isFileContext();
5452
5453 if (GlobalBlockExpr && !GlobalVarDecl) {
5454 Diags.Report(block->getLocation(), GlobalBlockRewriteFailedDiag);
5455 GlobalBlockExpr = false;
5456 }
5457
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005458 std::string BlockNumber = utostr(Blocks.size()-1);
5459
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005460 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
5461
5462 // Get a pointer to the function type so we can cast appropriately.
5463 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5464 QualType FType = Context->getPointerType(BFT);
5465
5466 FunctionDecl *FD;
5467 Expr *NewRep;
5468
Benjamin Kramere5753592013-09-09 14:48:42 +00005469 // Simulate a constructor call...
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00005470 std::string Tag;
5471
5472 if (GlobalBlockExpr)
5473 Tag = "__global_";
5474 else
5475 Tag = "__";
5476 Tag += FuncName + "_block_impl_" + BlockNumber;
5477
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005478 FD = SynthBlockInitFunctionDecl(Tag);
John McCallf4b88a42012-03-10 09:33:50 +00005479 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005480 SourceLocation());
5481
5482 SmallVector<Expr*, 4> InitExprs;
5483
5484 // Initialize the block function.
5485 FD = SynthBlockInitFunctionDecl(Func);
John McCallf4b88a42012-03-10 09:33:50 +00005486 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5487 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005488 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5489 CK_BitCast, Arg);
5490 InitExprs.push_back(castExpr);
5491
5492 // Initialize the block descriptor.
5493 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
5494
5495 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
5496 SourceLocation(), SourceLocation(),
5497 &Context->Idents.get(DescData.c_str()),
5498 Context->VoidPtrTy, 0,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00005499 SC_Static);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005500 UnaryOperator *DescRefExpr =
John McCallf4b88a42012-03-10 09:33:50 +00005501 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005502 Context->VoidPtrTy,
5503 VK_LValue,
5504 SourceLocation()),
5505 UO_AddrOf,
5506 Context->getPointerType(Context->VoidPtrTy),
5507 VK_RValue, OK_Ordinary,
5508 SourceLocation());
5509 InitExprs.push_back(DescRefExpr);
5510
5511 // Add initializers for any closure decl refs.
5512 if (BlockDeclRefs.size()) {
5513 Expr *Exp;
5514 // Output all "by copy" declarations.
Craig Topper09d19ef2013-07-04 03:08:24 +00005515 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005516 E = BlockByCopyDecls.end(); I != E; ++I) {
5517 if (isObjCType((*I)->getType())) {
5518 // FIXME: Conform to ABI ([[obj retain] autorelease]).
5519 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005520 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5521 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005522 if (HasLocalVariableExternalStorage(*I)) {
5523 QualType QT = (*I)->getType();
5524 QT = Context->getPointerType(QT);
5525 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5526 OK_Ordinary, SourceLocation());
5527 }
5528 } else if (isTopLevelBlockPointerType((*I)->getType())) {
5529 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005530 Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5531 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005532 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5533 CK_BitCast, Arg);
5534 } else {
5535 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005536 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5537 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005538 if (HasLocalVariableExternalStorage(*I)) {
5539 QualType QT = (*I)->getType();
5540 QT = Context->getPointerType(QT);
5541 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5542 OK_Ordinary, SourceLocation());
5543 }
5544
5545 }
5546 InitExprs.push_back(Exp);
5547 }
5548 // Output all "by ref" declarations.
Craig Topper09d19ef2013-07-04 03:08:24 +00005549 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005550 E = BlockByRefDecls.end(); I != E; ++I) {
5551 ValueDecl *ND = (*I);
5552 std::string Name(ND->getNameAsString());
5553 std::string RecName;
5554 RewriteByRefString(RecName, Name, ND, true);
5555 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5556 + sizeof("struct"));
5557 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5558 SourceLocation(), SourceLocation(),
5559 II);
5560 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5561 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5562
5563 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005564 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005565 SourceLocation());
5566 bool isNestedCapturedVar = false;
5567 if (block)
5568 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
5569 ce = block->capture_end(); ci != ce; ++ci) {
5570 const VarDecl *variable = ci->getVariable();
5571 if (variable == ND && ci->isNested()) {
5572 assert (ci->isByRef() &&
5573 "SynthBlockInitExpr - captured block variable is not byref");
5574 isNestedCapturedVar = true;
5575 break;
5576 }
5577 }
5578 // captured nested byref variable has its address passed. Do not take
5579 // its address again.
5580 if (!isNestedCapturedVar)
5581 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
5582 Context->getPointerType(Exp->getType()),
5583 VK_RValue, OK_Ordinary, SourceLocation());
5584 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
5585 InitExprs.push_back(Exp);
5586 }
5587 }
5588 if (ImportedBlockDecls.size()) {
5589 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5590 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
5591 unsigned IntSize =
5592 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5593 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5594 Context->IntTy, SourceLocation());
5595 InitExprs.push_back(FlagExp);
5596 }
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00005597 NewRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005598 FType, VK_LValue, SourceLocation());
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00005599
5600 if (GlobalBlockExpr) {
5601 assert (GlobalConstructionExp == 0 &&
5602 "SynthBlockInitExpr - GlobalConstructionExp must be null");
5603 GlobalConstructionExp = NewRep;
5604 NewRep = DRE;
5605 }
5606
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005607 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
5608 Context->getPointerType(NewRep->getType()),
5609 VK_RValue, OK_Ordinary, SourceLocation());
5610 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
5611 NewRep);
5612 BlockDeclRefs.clear();
5613 BlockByRefDecls.clear();
5614 BlockByRefDeclsPtrSet.clear();
5615 BlockByCopyDecls.clear();
5616 BlockByCopyDeclsPtrSet.clear();
5617 ImportedBlockDecls.clear();
5618 return NewRep;
5619}
5620
5621bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
5622 if (const ObjCForCollectionStmt * CS =
5623 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
5624 return CS->getElement() == DS;
5625 return false;
5626}
5627
5628//===----------------------------------------------------------------------===//
5629// Function Body / Expression rewriting
5630//===----------------------------------------------------------------------===//
5631
5632Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
5633 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5634 isa<DoStmt>(S) || isa<ForStmt>(S))
5635 Stmts.push_back(S);
5636 else if (isa<ObjCForCollectionStmt>(S)) {
5637 Stmts.push_back(S);
5638 ObjCBcLabelNo.push_back(++BcLabelCount);
5639 }
5640
5641 // Pseudo-object operations and ivar references need special
5642 // treatment because we're going to recursively rewrite them.
5643 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
5644 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
5645 return RewritePropertyOrImplicitSetter(PseudoOp);
5646 } else {
5647 return RewritePropertyOrImplicitGetter(PseudoOp);
5648 }
5649 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5650 return RewriteObjCIvarRefExpr(IvarRefExpr);
5651 }
Fariborz Jahanian9ffd1ae2013-02-08 18:57:50 +00005652 else if (isa<OpaqueValueExpr>(S))
5653 S = cast<OpaqueValueExpr>(S)->getSourceExpr();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005654
5655 SourceRange OrigStmtRange = S->getSourceRange();
5656
5657 // Perform a bottom up rewrite of all children.
5658 for (Stmt::child_range CI = S->children(); CI; ++CI)
5659 if (*CI) {
5660 Stmt *childStmt = (*CI);
5661 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
5662 if (newStmt) {
5663 *CI = newStmt;
5664 }
5665 }
5666
5667 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
John McCallf4b88a42012-03-10 09:33:50 +00005668 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005669 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5670 InnerContexts.insert(BE->getBlockDecl());
5671 ImportedLocalExternalDecls.clear();
5672 GetInnerBlockDeclRefExprs(BE->getBody(),
5673 InnerBlockDeclRefs, InnerContexts);
5674 // Rewrite the block body in place.
5675 Stmt *SaveCurrentBody = CurrentBody;
5676 CurrentBody = BE->getBody();
5677 PropParentMap = 0;
5678 // block literal on rhs of a property-dot-sytax assignment
5679 // must be replaced by its synthesize ast so getRewrittenText
5680 // works as expected. In this case, what actually ends up on RHS
5681 // is the blockTranscribed which is the helper function for the
5682 // block literal; as in: self.c = ^() {[ace ARR];};
5683 bool saveDisableReplaceStmt = DisableReplaceStmt;
5684 DisableReplaceStmt = false;
5685 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
5686 DisableReplaceStmt = saveDisableReplaceStmt;
5687 CurrentBody = SaveCurrentBody;
5688 PropParentMap = 0;
5689 ImportedLocalExternalDecls.clear();
5690 // Now we snarf the rewritten text and stash it away for later use.
5691 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
5692 RewrittenBlockExprs[BE] = Str;
5693
5694 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5695
5696 //blockTranscribed->dump();
5697 ReplaceStmt(S, blockTranscribed);
5698 return blockTranscribed;
5699 }
5700 // Handle specific things.
5701 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5702 return RewriteAtEncode(AtEncode);
5703
5704 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5705 return RewriteAtSelector(AtSelector);
5706
5707 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5708 return RewriteObjCStringLiteral(AtString);
Fariborz Jahanian55947042012-03-27 20:17:30 +00005709
5710 if (ObjCBoolLiteralExpr *BoolLitExpr = dyn_cast<ObjCBoolLiteralExpr>(S))
5711 return RewriteObjCBoolLiteralExpr(BoolLitExpr);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00005712
Patrick Beardeb382ec2012-04-19 00:25:12 +00005713 if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(S))
5714 return RewriteObjCBoxedExpr(BoxedExpr);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00005715
5716 if (ObjCArrayLiteral *ArrayLitExpr = dyn_cast<ObjCArrayLiteral>(S))
5717 return RewriteObjCArrayLiteralExpr(ArrayLitExpr);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00005718
5719 if (ObjCDictionaryLiteral *DictionaryLitExpr =
5720 dyn_cast<ObjCDictionaryLiteral>(S))
5721 return RewriteObjCDictionaryLiteralExpr(DictionaryLitExpr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005722
5723 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
5724#if 0
5725 // Before we rewrite it, put the original message expression in a comment.
5726 SourceLocation startLoc = MessExpr->getLocStart();
5727 SourceLocation endLoc = MessExpr->getLocEnd();
5728
5729 const char *startBuf = SM->getCharacterData(startLoc);
5730 const char *endBuf = SM->getCharacterData(endLoc);
5731
5732 std::string messString;
5733 messString += "// ";
5734 messString.append(startBuf, endBuf-startBuf+1);
5735 messString += "\n";
5736
5737 // FIXME: Missing definition of
5738 // InsertText(clang::SourceLocation, char const*, unsigned int).
5739 // InsertText(startLoc, messString.c_str(), messString.size());
5740 // Tried this, but it didn't work either...
5741 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
5742#endif
5743 return RewriteMessageExpr(MessExpr);
5744 }
5745
Fariborz Jahanian042b91d2012-05-23 23:47:20 +00005746 if (ObjCAutoreleasePoolStmt *StmtAutoRelease =
5747 dyn_cast<ObjCAutoreleasePoolStmt>(S)) {
5748 return RewriteObjCAutoreleasePoolStmt(StmtAutoRelease);
5749 }
5750
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005751 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5752 return RewriteObjCTryStmt(StmtTry);
5753
5754 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5755 return RewriteObjCSynchronizedStmt(StmtTry);
5756
5757 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5758 return RewriteObjCThrowStmt(StmtThrow);
5759
5760 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5761 return RewriteObjCProtocolExpr(ProtocolExp);
5762
5763 if (ObjCForCollectionStmt *StmtForCollection =
5764 dyn_cast<ObjCForCollectionStmt>(S))
5765 return RewriteObjCForCollectionStmt(StmtForCollection,
5766 OrigStmtRange.getEnd());
5767 if (BreakStmt *StmtBreakStmt =
5768 dyn_cast<BreakStmt>(S))
5769 return RewriteBreakStmt(StmtBreakStmt);
5770 if (ContinueStmt *StmtContinueStmt =
5771 dyn_cast<ContinueStmt>(S))
5772 return RewriteContinueStmt(StmtContinueStmt);
5773
5774 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
5775 // and cast exprs.
5776 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5777 // FIXME: What we're doing here is modifying the type-specifier that
5778 // precedes the first Decl. In the future the DeclGroup should have
5779 // a separate type-specifier that we can rewrite.
5780 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5781 // the context of an ObjCForCollectionStmt. For example:
5782 // NSArray *someArray;
5783 // for (id <FooProtocol> index in someArray) ;
5784 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5785 // and it depends on the original text locations/positions.
5786 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
5787 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
5788
5789 // Blocks rewrite rules.
5790 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5791 DI != DE; ++DI) {
5792 Decl *SD = *DI;
5793 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
5794 if (isTopLevelBlockPointerType(ND->getType()))
5795 RewriteBlockPointerDecl(ND);
5796 else if (ND->getType()->isFunctionPointerType())
5797 CheckFunctionPointerDecl(ND->getType(), ND);
5798 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
5799 if (VD->hasAttr<BlocksAttr>()) {
5800 static unsigned uniqueByrefDeclCount = 0;
5801 assert(!BlockByRefDeclNo.count(ND) &&
5802 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5803 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00005804 RewriteByRefVar(VD, (DI == DS->decl_begin()), ((DI+1) == DE));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005805 }
5806 else
5807 RewriteTypeOfDecl(VD);
5808 }
5809 }
5810 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
5811 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5812 RewriteBlockPointerDecl(TD);
5813 else if (TD->getUnderlyingType()->isFunctionPointerType())
5814 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5815 }
5816 }
5817 }
5818
5819 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5820 RewriteObjCQualifiedInterfaceTypes(CE);
5821
5822 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5823 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5824 assert(!Stmts.empty() && "Statement stack is empty");
5825 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5826 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
5827 && "Statement stack mismatch");
5828 Stmts.pop_back();
5829 }
5830 // Handle blocks rewriting.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005831 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5832 ValueDecl *VD = DRE->getDecl();
5833 if (VD->hasAttr<BlocksAttr>())
5834 return RewriteBlockDeclRefExpr(DRE);
5835 if (HasLocalVariableExternalStorage(VD))
5836 return RewriteLocalVariableExternalStorage(DRE);
5837 }
5838
5839 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
5840 if (CE->getCallee()->getType()->isBlockPointerType()) {
5841 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
5842 ReplaceStmt(S, BlockCall);
5843 return BlockCall;
5844 }
5845 }
5846 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
5847 RewriteCastExpr(CE);
5848 }
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00005849 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5850 RewriteImplicitCastObjCExpr(ICE);
5851 }
Fariborz Jahanian43aa1c32012-04-16 22:14:01 +00005852#if 0
Fariborz Jahanian653b7cf2012-04-13 18:00:54 +00005853
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005854 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5855 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5856 ICE->getSubExpr(),
5857 SourceLocation());
5858 // Get the new text.
5859 std::string SStr;
5860 llvm::raw_string_ostream Buf(SStr);
Richard Smithd1420c62012-08-16 03:56:14 +00005861 Replacement->printPretty(Buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005862 const std::string &Str = Buf.str();
5863
5864 printf("CAST = %s\n", &Str[0]);
5865 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5866 delete S;
5867 return Replacement;
5868 }
5869#endif
5870 // Return this stmt unmodified.
5871 return S;
5872}
5873
5874void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
5875 for (RecordDecl::field_iterator i = RD->field_begin(),
5876 e = RD->field_end(); i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00005877 FieldDecl *FD = *i;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005878 if (isTopLevelBlockPointerType(FD->getType()))
5879 RewriteBlockPointerDecl(FD);
5880 if (FD->getType()->isObjCQualifiedIdType() ||
5881 FD->getType()->isObjCQualifiedInterfaceType())
5882 RewriteObjCQualifiedInterfaceTypes(FD);
5883 }
5884}
5885
5886/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5887/// main file of the input.
5888void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
5889 switch (D->getKind()) {
5890 case Decl::Function: {
5891 FunctionDecl *FD = cast<FunctionDecl>(D);
5892 if (FD->isOverloadedOperator())
5893 return;
5894
5895 // Since function prototypes don't have ParmDecl's, we check the function
5896 // prototype. This enables us to rewrite function declarations and
5897 // definitions using the same code.
5898 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
5899
Argyrios Kyrtzidis9335df32012-02-12 04:48:45 +00005900 if (!FD->isThisDeclarationADefinition())
5901 break;
5902
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005903 // FIXME: If this should support Obj-C++, support CXXTryStmt
5904 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
5905 CurFunctionDef = FD;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005906 CurrentBody = Body;
5907 Body =
5908 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5909 FD->setBody(Body);
5910 CurrentBody = 0;
5911 if (PropParentMap) {
5912 delete PropParentMap;
5913 PropParentMap = 0;
5914 }
5915 // This synthesizes and inserts the block "impl" struct, invoke function,
5916 // and any copy/dispose helper functions.
5917 InsertBlockLiteralsWithinFunction(FD);
Fariborz Jahanian96205962012-11-06 17:30:23 +00005918 RewriteLineDirective(D);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005919 CurFunctionDef = 0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005920 }
5921 break;
5922 }
5923 case Decl::ObjCMethod: {
5924 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
5925 if (CompoundStmt *Body = MD->getCompoundBody()) {
5926 CurMethodDef = MD;
5927 CurrentBody = Body;
5928 Body =
5929 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5930 MD->setBody(Body);
5931 CurrentBody = 0;
5932 if (PropParentMap) {
5933 delete PropParentMap;
5934 PropParentMap = 0;
5935 }
5936 InsertBlockLiteralsWithinMethod(MD);
Fariborz Jahanian96205962012-11-06 17:30:23 +00005937 RewriteLineDirective(D);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005938 CurMethodDef = 0;
5939 }
5940 break;
5941 }
5942 case Decl::ObjCImplementation: {
5943 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
5944 ClassImplementation.push_back(CI);
5945 break;
5946 }
5947 case Decl::ObjCCategoryImpl: {
5948 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
5949 CategoryImplementation.push_back(CI);
5950 break;
5951 }
5952 case Decl::Var: {
5953 VarDecl *VD = cast<VarDecl>(D);
5954 RewriteObjCQualifiedInterfaceTypes(VD);
5955 if (isTopLevelBlockPointerType(VD->getType()))
5956 RewriteBlockPointerDecl(VD);
5957 else if (VD->getType()->isFunctionPointerType()) {
5958 CheckFunctionPointerDecl(VD->getType(), VD);
5959 if (VD->getInit()) {
5960 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5961 RewriteCastExpr(CE);
5962 }
5963 }
5964 } else if (VD->getType()->isRecordType()) {
5965 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5966 if (RD->isCompleteDefinition())
5967 RewriteRecordBody(RD);
5968 }
5969 if (VD->getInit()) {
5970 GlobalVarDecl = VD;
5971 CurrentBody = VD->getInit();
5972 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
5973 CurrentBody = 0;
5974 if (PropParentMap) {
5975 delete PropParentMap;
5976 PropParentMap = 0;
5977 }
5978 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
5979 GlobalVarDecl = 0;
5980
5981 // This is needed for blocks.
5982 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5983 RewriteCastExpr(CE);
5984 }
5985 }
5986 break;
5987 }
5988 case Decl::TypeAlias:
5989 case Decl::Typedef: {
5990 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
5991 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5992 RewriteBlockPointerDecl(TD);
5993 else if (TD->getUnderlyingType()->isFunctionPointerType())
5994 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
Fariborz Jahanianf9f30792013-04-03 19:11:21 +00005995 else
5996 RewriteObjCQualifiedInterfaceTypes(TD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005997 }
5998 break;
5999 }
6000 case Decl::CXXRecord:
6001 case Decl::Record: {
6002 RecordDecl *RD = cast<RecordDecl>(D);
6003 if (RD->isCompleteDefinition())
6004 RewriteRecordBody(RD);
6005 break;
6006 }
6007 default:
6008 break;
6009 }
6010 // Nothing yet.
6011}
6012
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006013/// Write_ProtocolExprReferencedMetadata - This routine writer out the
6014/// protocol reference symbols in the for of:
6015/// struct _protocol_t *PROTOCOL_REF = &PROTOCOL_METADATA.
6016static void Write_ProtocolExprReferencedMetadata(ASTContext *Context,
6017 ObjCProtocolDecl *PDecl,
6018 std::string &Result) {
6019 // Also output .objc_protorefs$B section and its meta-data.
6020 if (Context->getLangOpts().MicrosoftExt)
Fariborz Jahanianbd78cfa2012-04-27 21:39:49 +00006021 Result += "static ";
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006022 Result += "struct _protocol_t *";
6023 Result += "_OBJC_PROTOCOL_REFERENCE_$_";
6024 Result += PDecl->getNameAsString();
6025 Result += " = &";
6026 Result += "_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
6027 Result += ";\n";
6028}
6029
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006030void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
6031 if (Diags.hasErrorOccurred())
6032 return;
6033
6034 RewriteInclude();
6035
Fariborz Jahanian31c4a4b2013-02-07 22:50:40 +00006036 for (unsigned i = 0, e = FunctionDefinitionsSeen.size(); i < e; i++) {
6037 // translation of function bodies were postponed untill all class and
6038 // their extensions and implementations are seen. This is because, we
6039 // cannot build grouping structs for bitfields untill they are all seen.
6040 FunctionDecl *FDecl = FunctionDefinitionsSeen[i];
6041 HandleTopLevelSingleDecl(FDecl);
6042 }
6043
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006044 // Here's a great place to add any extra declarations that may be needed.
6045 // Write out meta data for each @protocol(<expr>).
6046 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006047 E = ProtocolExprDecls.end(); I != E; ++I) {
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006048 RewriteObjCProtocolMetaData(*I, Preamble);
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006049 Write_ProtocolExprReferencedMetadata(Context, (*I), Preamble);
6050 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006051
6052 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +00006053
6054 if (ClassImplementation.size() || CategoryImplementation.size())
6055 RewriteImplementations();
6056
Fariborz Jahanian57317782012-02-21 23:58:41 +00006057 for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) {
6058 ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i];
6059 // Write struct declaration for the class matching its ivar declarations.
6060 // Note that for modern abi, this is postponed until the end of TU
6061 // because class extensions and the implementation might declare their own
6062 // private ivars.
6063 RewriteInterfaceDecl(CDecl);
6064 }
Fariborz Jahanian31c4a4b2013-02-07 22:50:40 +00006065
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006066 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
6067 // we are done.
6068 if (const RewriteBuffer *RewriteBuf =
6069 Rewrite.getRewriteBufferFor(MainFileID)) {
6070 //printf("Changed:\n");
6071 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
6072 } else {
6073 llvm::errs() << "No changes\n";
6074 }
6075
6076 if (ClassImplementation.size() || CategoryImplementation.size() ||
6077 ProtocolExprDecls.size()) {
6078 // Rewrite Objective-c meta data*
6079 std::string ResultStr;
6080 RewriteMetaDataIntoBuffer(ResultStr);
6081 // Emit metadata.
6082 *OutFile << ResultStr;
6083 }
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006084 // Emit ImageInfo;
6085 {
6086 std::string ResultStr;
6087 WriteImageInfo(ResultStr);
6088 *OutFile << ResultStr;
6089 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006090 OutFile->flush();
6091}
6092
6093void RewriteModernObjC::Initialize(ASTContext &context) {
6094 InitializeCommon(context);
6095
Fariborz Jahanian6991bc52012-03-10 17:45:38 +00006096 Preamble += "#ifndef __OBJC2__\n";
6097 Preamble += "#define __OBJC2__\n";
6098 Preamble += "#endif\n";
6099
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006100 // declaring objc_selector outside the parameter list removes a silly
6101 // scope related warning...
6102 if (IsHeader)
6103 Preamble = "#pragma once\n";
6104 Preamble += "struct objc_selector; struct objc_class;\n";
Fariborz Jahaniane2d87bc2012-04-12 23:52:52 +00006105 Preamble += "struct __rw_objc_super { \n\tstruct objc_object *object; ";
6106 Preamble += "\n\tstruct objc_object *superClass; ";
6107 // Add a constructor for creating temporary objects.
6108 Preamble += "\n\t__rw_objc_super(struct objc_object *o, struct objc_object *s) ";
6109 Preamble += ": object(o), superClass(s) {} ";
6110 Preamble += "\n};\n";
6111
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006112 if (LangOpts.MicrosoftExt) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006113 // Define all sections using syntax that makes sense.
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006114 // These are currently generated.
6115 Preamble += "\n#pragma section(\".objc_classlist$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006116 Preamble += "#pragma section(\".objc_catlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006117 Preamble += "#pragma section(\".objc_imageinfo$B\", long, read, write)\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006118 Preamble += "#pragma section(\".objc_nlclslist$B\", long, read, write)\n";
6119 Preamble += "#pragma section(\".objc_nlcatlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006120 // These are generated but not necessary for functionality.
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006121 Preamble += "#pragma section(\".cat_cls_meth$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006122 Preamble += "#pragma section(\".inst_meth$B\", long, read, write)\n";
6123 Preamble += "#pragma section(\".cls_meth$B\", long, read, write)\n";
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00006124 Preamble += "#pragma section(\".objc_ivar$B\", long, read, write)\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006125
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006126 // These need be generated for performance. Currently they are not,
6127 // using API calls instead.
6128 Preamble += "#pragma section(\".objc_selrefs$B\", long, read, write)\n";
6129 Preamble += "#pragma section(\".objc_classrefs$B\", long, read, write)\n";
6130 Preamble += "#pragma section(\".objc_superrefs$B\", long, read, write)\n";
6131
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006132 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006133 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
6134 Preamble += "typedef struct objc_object Protocol;\n";
6135 Preamble += "#define _REWRITER_typedef_Protocol\n";
6136 Preamble += "#endif\n";
6137 if (LangOpts.MicrosoftExt) {
6138 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
6139 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
Fariborz Jahanian5cf6b6c2012-03-21 23:41:04 +00006140 }
6141 else
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006142 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Fariborz Jahanian5cf6b6c2012-03-21 23:41:04 +00006143
6144 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend(void);\n";
6145 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper(void);\n";
6146 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_stret(void);\n";
6147 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper_stret(void);\n";
6148 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_fpret(void);\n";
6149
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00006150 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getClass";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006151 Preamble += "(const char *);\n";
6152 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
6153 Preamble += "(struct objc_class *);\n";
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00006154 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getMetaClass";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006155 Preamble += "(const char *);\n";
Fariborz Jahanian55261af2012-03-19 18:11:32 +00006156 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw( struct objc_object *);\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006157 // @synchronized hooks.
Aaron Ballman2d234d732012-09-06 16:44:16 +00006158 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_enter( struct objc_object *);\n";
6159 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_exit( struct objc_object *);\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006160 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Fariborz Jahaniane38f08a2013-09-05 17:17:32 +00006161 Preamble += "#ifdef _WIN64\n";
6162 Preamble += "typedef unsigned long long _WIN_NSUInteger;\n";
6163 Preamble += "#else\n";
6164 Preamble += "typedef unsigned int _WIN_NSUInteger;\n";
6165 Preamble += "#endif\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006166 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
6167 Preamble += "struct __objcFastEnumerationState {\n\t";
6168 Preamble += "unsigned long state;\n\t";
6169 Preamble += "void **itemsPtr;\n\t";
6170 Preamble += "unsigned long *mutationsPtr;\n\t";
6171 Preamble += "unsigned long extra[5];\n};\n";
6172 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
6173 Preamble += "#define __FASTENUMERATIONSTATE\n";
6174 Preamble += "#endif\n";
6175 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
6176 Preamble += "struct __NSConstantStringImpl {\n";
6177 Preamble += " int *isa;\n";
6178 Preamble += " int flags;\n";
6179 Preamble += " char *str;\n";
6180 Preamble += " long length;\n";
6181 Preamble += "};\n";
6182 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
6183 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
6184 Preamble += "#else\n";
6185 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
6186 Preamble += "#endif\n";
6187 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
6188 Preamble += "#endif\n";
6189 // Blocks preamble.
6190 Preamble += "#ifndef BLOCK_IMPL\n";
6191 Preamble += "#define BLOCK_IMPL\n";
6192 Preamble += "struct __block_impl {\n";
6193 Preamble += " void *isa;\n";
6194 Preamble += " int Flags;\n";
6195 Preamble += " int Reserved;\n";
6196 Preamble += " void *FuncPtr;\n";
6197 Preamble += "};\n";
6198 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
6199 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
6200 Preamble += "extern \"C\" __declspec(dllexport) "
6201 "void _Block_object_assign(void *, const void *, const int);\n";
6202 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
6203 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
6204 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
6205 Preamble += "#else\n";
6206 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
6207 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
6208 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
6209 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
6210 Preamble += "#endif\n";
6211 Preamble += "#endif\n";
6212 if (LangOpts.MicrosoftExt) {
6213 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
6214 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
6215 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
6216 Preamble += "#define __attribute__(X)\n";
6217 Preamble += "#endif\n";
Fariborz Jahanian5ce28272012-04-12 16:33:31 +00006218 Preamble += "#ifndef __weak\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006219 Preamble += "#define __weak\n";
Fariborz Jahanian5ce28272012-04-12 16:33:31 +00006220 Preamble += "#endif\n";
6221 Preamble += "#ifndef __block\n";
6222 Preamble += "#define __block\n";
6223 Preamble += "#endif\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006224 }
6225 else {
6226 Preamble += "#define __block\n";
6227 Preamble += "#define __weak\n";
6228 }
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00006229
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00006230 // Declarations required for modern objective-c array and dictionary literals.
6231 Preamble += "\n#include <stdarg.h>\n";
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00006232 Preamble += "struct __NSContainer_literal {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00006233 Preamble += " void * *arr;\n";
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00006234 Preamble += " __NSContainer_literal (unsigned int count, ...) {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00006235 Preamble += "\tva_list marker;\n";
6236 Preamble += "\tva_start(marker, count);\n";
6237 Preamble += "\tarr = new void *[count];\n";
6238 Preamble += "\tfor (unsigned i = 0; i < count; i++)\n";
6239 Preamble += "\t arr[i] = va_arg(marker, void *);\n";
6240 Preamble += "\tva_end( marker );\n";
6241 Preamble += " };\n";
Fariborz Jahanian13a9c022012-05-02 23:53:46 +00006242 Preamble += " ~__NSContainer_literal() {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00006243 Preamble += "\tdelete[] arr;\n";
6244 Preamble += " }\n";
6245 Preamble += "};\n";
6246
Fariborz Jahanian042b91d2012-05-23 23:47:20 +00006247 // Declaration required for implementation of @autoreleasepool statement.
6248 Preamble += "extern \"C\" __declspec(dllimport) void * objc_autoreleasePoolPush(void);\n";
6249 Preamble += "extern \"C\" __declspec(dllimport) void objc_autoreleasePoolPop(void *);\n\n";
6250 Preamble += "struct __AtAutoreleasePool {\n";
6251 Preamble += " __AtAutoreleasePool() {atautoreleasepoolobj = objc_autoreleasePoolPush();}\n";
6252 Preamble += " ~__AtAutoreleasePool() {objc_autoreleasePoolPop(atautoreleasepoolobj);}\n";
6253 Preamble += " void * atautoreleasepoolobj;\n";
6254 Preamble += "};\n";
6255
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006256 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
6257 // as this avoids warning in any 64bit/32bit compilation model.
6258 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
6259}
6260
6261/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
6262/// ivar offset.
6263void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
6264 std::string &Result) {
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00006265 Result += "__OFFSETOFIVAR__(struct ";
6266 Result += ivar->getContainingInterface()->getNameAsString();
6267 if (LangOpts.MicrosoftExt)
6268 Result += "_IMPL";
6269 Result += ", ";
6270 if (ivar->isBitField())
6271 ObjCIvarBitfieldGroupDecl(ivar, Result);
6272 else
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006273 Result += ivar->getNameAsString();
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00006274 Result += ")";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006275}
6276
6277/// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
6278/// struct _prop_t {
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006279/// const char *name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006280/// char *attributes;
6281/// }
6282
6283/// struct _prop_list_t {
6284/// uint32_t entsize; // sizeof(struct _prop_t)
6285/// uint32_t count_of_properties;
6286/// struct _prop_t prop_list[count_of_properties];
6287/// }
6288
6289/// struct _protocol_t;
6290
6291/// struct _protocol_list_t {
6292/// long protocol_count; // Note, this is 32/64 bit
6293/// struct _protocol_t * protocol_list[protocol_count];
6294/// }
6295
6296/// struct _objc_method {
6297/// SEL _cmd;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006298/// const char *method_type;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006299/// char *_imp;
6300/// }
6301
6302/// struct _method_list_t {
6303/// uint32_t entsize; // sizeof(struct _objc_method)
6304/// uint32_t method_count;
6305/// struct _objc_method method_list[method_count];
6306/// }
6307
6308/// struct _protocol_t {
6309/// id isa; // NULL
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006310/// const char *protocol_name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006311/// const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006312/// const struct method_list_t *instance_methods;
6313/// const struct method_list_t *class_methods;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006314/// const struct method_list_t *optionalInstanceMethods;
6315/// const struct method_list_t *optionalClassMethods;
6316/// const struct _prop_list_t * properties;
6317/// const uint32_t size; // sizeof(struct _protocol_t)
6318/// const uint32_t flags; // = 0
6319/// const char ** extendedMethodTypes;
6320/// }
6321
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006322/// struct _ivar_t {
6323/// unsigned long int *offset; // pointer to ivar offset location
Fariborz Jahanianae932952012-02-10 20:47:10 +00006324/// const char *name;
6325/// const char *type;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006326/// uint32_t alignment;
6327/// uint32_t size;
6328/// }
6329
6330/// struct _ivar_list_t {
6331/// uint32 entsize; // sizeof(struct _ivar_t)
6332/// uint32 count;
Fariborz Jahanianae932952012-02-10 20:47:10 +00006333/// struct _ivar_t list[count];
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006334/// }
6335
6336/// struct _class_ro_t {
Fariborz Jahanian249cd102012-03-24 16:53:16 +00006337/// uint32_t flags;
6338/// uint32_t instanceStart;
6339/// uint32_t instanceSize;
6340/// uint32_t reserved; // only when building for 64bit targets
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006341/// const uint8_t *ivarLayout;
6342/// const char *name;
6343/// const struct _method_list_t *baseMethods;
6344/// const struct _protocol_list_t *baseProtocols;
6345/// const struct _ivar_list_t *ivars;
6346/// const uint8_t *weakIvarLayout;
6347/// const struct _prop_list_t *properties;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006348/// }
6349
6350/// struct _class_t {
6351/// struct _class_t *isa;
Fariborz Jahanianfd4ce2c2012-03-20 17:34:50 +00006352/// struct _class_t *superclass;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006353/// void *cache;
6354/// IMP *vtable;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006355/// struct _class_ro_t *ro;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006356/// }
6357
6358/// struct _category_t {
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006359/// const char *name;
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006360/// struct _class_t *cls;
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006361/// const struct _method_list_t *instance_methods;
6362/// const struct _method_list_t *class_methods;
6363/// const struct _protocol_list_t *protocols;
6364/// const struct _prop_list_t *properties;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006365/// }
6366
6367/// MessageRefTy - LLVM for:
6368/// struct _message_ref_t {
6369/// IMP messenger;
6370/// SEL name;
6371/// };
6372
6373/// SuperMessageRefTy - LLVM for:
6374/// struct _super_message_ref_t {
6375/// SUPER_IMP messenger;
6376/// SEL name;
6377/// };
6378
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006379static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006380 static bool meta_data_declared = false;
6381 if (meta_data_declared)
6382 return;
6383
6384 Result += "\nstruct _prop_t {\n";
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006385 Result += "\tconst char *name;\n";
6386 Result += "\tconst char *attributes;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006387 Result += "};\n";
6388
6389 Result += "\nstruct _protocol_t;\n";
6390
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006391 Result += "\nstruct _objc_method {\n";
6392 Result += "\tstruct objc_selector * _cmd;\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006393 Result += "\tconst char *method_type;\n";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006394 Result += "\tvoid *_imp;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006395 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006396
6397 Result += "\nstruct _protocol_t {\n";
6398 Result += "\tvoid * isa; // NULL\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006399 Result += "\tconst char *protocol_name;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006400 Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006401 Result += "\tconst struct method_list_t *instance_methods;\n";
6402 Result += "\tconst struct method_list_t *class_methods;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006403 Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
6404 Result += "\tconst struct method_list_t *optionalClassMethods;\n";
6405 Result += "\tconst struct _prop_list_t * properties;\n";
6406 Result += "\tconst unsigned int size; // sizeof(struct _protocol_t)\n";
6407 Result += "\tconst unsigned int flags; // = 0\n";
6408 Result += "\tconst char ** extendedMethodTypes;\n";
6409 Result += "};\n";
6410
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006411 Result += "\nstruct _ivar_t {\n";
6412 Result += "\tunsigned long int *offset; // pointer to ivar offset location\n";
Fariborz Jahanianae932952012-02-10 20:47:10 +00006413 Result += "\tconst char *name;\n";
6414 Result += "\tconst char *type;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006415 Result += "\tunsigned int alignment;\n";
6416 Result += "\tunsigned int size;\n";
6417 Result += "};\n";
6418
6419 Result += "\nstruct _class_ro_t {\n";
Fariborz Jahanian249cd102012-03-24 16:53:16 +00006420 Result += "\tunsigned int flags;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006421 Result += "\tunsigned int instanceStart;\n";
Fariborz Jahanian249cd102012-03-24 16:53:16 +00006422 Result += "\tunsigned int instanceSize;\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006423 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6424 if (Triple.getArch() == llvm::Triple::x86_64)
Fariborz Jahanian249cd102012-03-24 16:53:16 +00006425 Result += "\tunsigned int reserved;\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006426 Result += "\tconst unsigned char *ivarLayout;\n";
6427 Result += "\tconst char *name;\n";
6428 Result += "\tconst struct _method_list_t *baseMethods;\n";
6429 Result += "\tconst struct _objc_protocol_list *baseProtocols;\n";
6430 Result += "\tconst struct _ivar_list_t *ivars;\n";
6431 Result += "\tconst unsigned char *weakIvarLayout;\n";
6432 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006433 Result += "};\n";
6434
6435 Result += "\nstruct _class_t {\n";
6436 Result += "\tstruct _class_t *isa;\n";
Fariborz Jahanianfd4ce2c2012-03-20 17:34:50 +00006437 Result += "\tstruct _class_t *superclass;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006438 Result += "\tvoid *cache;\n";
6439 Result += "\tvoid *vtable;\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006440 Result += "\tstruct _class_ro_t *ro;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006441 Result += "};\n";
6442
6443 Result += "\nstruct _category_t {\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006444 Result += "\tconst char *name;\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006445 Result += "\tstruct _class_t *cls;\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006446 Result += "\tconst struct _method_list_t *instance_methods;\n";
6447 Result += "\tconst struct _method_list_t *class_methods;\n";
6448 Result += "\tconst struct _protocol_list_t *protocols;\n";
6449 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006450 Result += "};\n";
6451
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006452 Result += "extern \"C\" __declspec(dllimport) struct objc_cache _objc_empty_cache;\n";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006453 Result += "#pragma warning(disable:4273)\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006454 meta_data_declared = true;
6455}
6456
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006457static void Write_protocol_list_t_TypeDecl(std::string &Result,
6458 long super_protocol_count) {
6459 Result += "struct /*_protocol_list_t*/"; Result += " {\n";
6460 Result += "\tlong protocol_count; // Note, this is 32/64 bit\n";
6461 Result += "\tstruct _protocol_t *super_protocols[";
6462 Result += utostr(super_protocol_count); Result += "];\n";
6463 Result += "}";
6464}
6465
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006466static void Write_method_list_t_TypeDecl(std::string &Result,
6467 unsigned int method_count) {
6468 Result += "struct /*_method_list_t*/"; Result += " {\n";
6469 Result += "\tunsigned int entsize; // sizeof(struct _objc_method)\n";
6470 Result += "\tunsigned int method_count;\n";
6471 Result += "\tstruct _objc_method method_list[";
6472 Result += utostr(method_count); Result += "];\n";
6473 Result += "}";
6474}
6475
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006476static void Write__prop_list_t_TypeDecl(std::string &Result,
6477 unsigned int property_count) {
6478 Result += "struct /*_prop_list_t*/"; Result += " {\n";
6479 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6480 Result += "\tunsigned int count_of_properties;\n";
6481 Result += "\tstruct _prop_t prop_list[";
6482 Result += utostr(property_count); Result += "];\n";
6483 Result += "}";
6484}
6485
Fariborz Jahanianae932952012-02-10 20:47:10 +00006486static void Write__ivar_list_t_TypeDecl(std::string &Result,
6487 unsigned int ivar_count) {
6488 Result += "struct /*_ivar_list_t*/"; Result += " {\n";
6489 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6490 Result += "\tunsigned int count;\n";
6491 Result += "\tstruct _ivar_t ivar_list[";
6492 Result += utostr(ivar_count); Result += "];\n";
6493 Result += "}";
6494}
6495
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006496static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result,
6497 ArrayRef<ObjCProtocolDecl *> SuperProtocols,
6498 StringRef VarName,
6499 StringRef ProtocolName) {
6500 if (SuperProtocols.size() > 0) {
6501 Result += "\nstatic ";
6502 Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size());
6503 Result += " "; Result += VarName;
6504 Result += ProtocolName;
6505 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6506 Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n";
6507 for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) {
6508 ObjCProtocolDecl *SuperPD = SuperProtocols[i];
6509 Result += "\t&"; Result += "_OBJC_PROTOCOL_";
6510 Result += SuperPD->getNameAsString();
6511 if (i == e-1)
6512 Result += "\n};\n";
6513 else
6514 Result += ",\n";
6515 }
6516 }
6517}
6518
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006519static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj,
6520 ASTContext *Context, std::string &Result,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006521 ArrayRef<ObjCMethodDecl *> Methods,
6522 StringRef VarName,
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006523 StringRef TopLevelDeclName,
6524 bool MethodImpl) {
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006525 if (Methods.size() > 0) {
6526 Result += "\nstatic ";
6527 Write_method_list_t_TypeDecl(Result, Methods.size());
6528 Result += " "; Result += VarName;
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006529 Result += TopLevelDeclName;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006530 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6531 Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
6532 Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
6533 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6534 ObjCMethodDecl *MD = Methods[i];
6535 if (i == 0)
6536 Result += "\t{{(struct objc_selector *)\"";
6537 else
6538 Result += "\t{(struct objc_selector *)\"";
6539 Result += (MD)->getSelector().getAsString(); Result += "\"";
6540 Result += ", ";
6541 std::string MethodTypeString;
6542 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString);
6543 Result += "\""; Result += MethodTypeString; Result += "\"";
6544 Result += ", ";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006545 if (!MethodImpl)
6546 Result += "0";
6547 else {
6548 Result += "(void *)";
6549 Result += RewriteObj.MethodInternalNames[MD];
6550 }
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006551 if (i == e-1)
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006552 Result += "}}\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006553 else
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006554 Result += "},\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006555 }
6556 Result += "};\n";
6557 }
6558}
6559
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006560static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006561 ASTContext *Context, std::string &Result,
6562 ArrayRef<ObjCPropertyDecl *> Properties,
6563 const Decl *Container,
6564 StringRef VarName,
6565 StringRef ProtocolName) {
6566 if (Properties.size() > 0) {
6567 Result += "\nstatic ";
6568 Write__prop_list_t_TypeDecl(Result, Properties.size());
6569 Result += " "; Result += VarName;
6570 Result += ProtocolName;
6571 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6572 Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
6573 Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
6574 for (unsigned i = 0, e = Properties.size(); i < e; i++) {
6575 ObjCPropertyDecl *PropDecl = Properties[i];
6576 if (i == 0)
6577 Result += "\t{{\"";
6578 else
6579 Result += "\t{\"";
6580 Result += PropDecl->getName(); Result += "\",";
6581 std::string PropertyTypeString, QuotePropertyTypeString;
6582 Context->getObjCEncodingForPropertyDecl(PropDecl, Container, PropertyTypeString);
6583 RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
6584 Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
6585 if (i == e-1)
6586 Result += "}}\n";
6587 else
6588 Result += "},\n";
6589 }
6590 Result += "};\n";
6591 }
6592}
6593
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006594// Metadata flags
6595enum MetaDataDlags {
6596 CLS = 0x0,
6597 CLS_META = 0x1,
6598 CLS_ROOT = 0x2,
6599 OBJC2_CLS_HIDDEN = 0x10,
6600 CLS_EXCEPTION = 0x20,
6601
6602 /// (Obsolete) ARC-specific: this class has a .release_ivars method
6603 CLS_HAS_IVAR_RELEASER = 0x40,
6604 /// class was compiled with -fobjc-arr
6605 CLS_COMPILED_BY_ARC = 0x80 // (1<<7)
6606};
6607
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006608static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result,
6609 unsigned int flags,
6610 const std::string &InstanceStart,
6611 const std::string &InstanceSize,
6612 ArrayRef<ObjCMethodDecl *>baseMethods,
6613 ArrayRef<ObjCProtocolDecl *>baseProtocols,
6614 ArrayRef<ObjCIvarDecl *>ivars,
6615 ArrayRef<ObjCPropertyDecl *>Properties,
6616 StringRef VarName,
6617 StringRef ClassName) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006618 Result += "\nstatic struct _class_ro_t ";
6619 Result += VarName; Result += ClassName;
6620 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6621 Result += "\t";
6622 Result += llvm::utostr(flags); Result += ", ";
6623 Result += InstanceStart; Result += ", ";
6624 Result += InstanceSize; Result += ", \n";
6625 Result += "\t";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006626 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6627 if (Triple.getArch() == llvm::Triple::x86_64)
6628 // uint32_t const reserved; // only when building for 64bit targets
6629 Result += "(unsigned int)0, \n\t";
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006630 // const uint8_t * const ivarLayout;
6631 Result += "0, \n\t";
6632 Result += "\""; Result += ClassName; Result += "\",\n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006633 bool metaclass = ((flags & CLS_META) != 0);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006634 if (baseMethods.size() > 0) {
6635 Result += "(const struct _method_list_t *)&";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006636 if (metaclass)
6637 Result += "_OBJC_$_CLASS_METHODS_";
6638 else
6639 Result += "_OBJC_$_INSTANCE_METHODS_";
6640 Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006641 Result += ",\n\t";
6642 }
6643 else
6644 Result += "0, \n\t";
6645
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006646 if (!metaclass && baseProtocols.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006647 Result += "(const struct _objc_protocol_list *)&";
6648 Result += "_OBJC_CLASS_PROTOCOLS_$_"; Result += ClassName;
6649 Result += ",\n\t";
6650 }
6651 else
6652 Result += "0, \n\t";
6653
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006654 if (!metaclass && ivars.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006655 Result += "(const struct _ivar_list_t *)&";
6656 Result += "_OBJC_$_INSTANCE_VARIABLES_"; Result += ClassName;
6657 Result += ",\n\t";
6658 }
6659 else
6660 Result += "0, \n\t";
6661
6662 // weakIvarLayout
6663 Result += "0, \n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006664 if (!metaclass && Properties.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006665 Result += "(const struct _prop_list_t *)&";
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00006666 Result += "_OBJC_$_PROP_LIST_"; Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006667 Result += ",\n";
6668 }
6669 else
6670 Result += "0, \n";
6671
6672 Result += "};\n";
6673}
6674
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006675static void Write_class_t(ASTContext *Context, std::string &Result,
6676 StringRef VarName,
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006677 const ObjCInterfaceDecl *CDecl, bool metaclass) {
6678 bool rootClass = (!CDecl->getSuperClass());
6679 const ObjCInterfaceDecl *RootClass = CDecl;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006680
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006681 if (!rootClass) {
6682 // Find the Root class
6683 RootClass = CDecl->getSuperClass();
6684 while (RootClass->getSuperClass()) {
6685 RootClass = RootClass->getSuperClass();
6686 }
6687 }
6688
6689 if (metaclass && rootClass) {
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006690 // Need to handle a case of use of forward declaration.
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006691 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006692 Result += "extern \"C\" ";
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006693 if (CDecl->getImplementation())
6694 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006695 else
6696 Result += "__declspec(dllimport) ";
6697
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006698 Result += "struct _class_t OBJC_CLASS_$_";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006699 Result += CDecl->getNameAsString();
6700 Result += ";\n";
6701 }
6702 // Also, for possibility of 'super' metadata class not having been defined yet.
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006703 if (!rootClass) {
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006704 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006705 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006706 Result += "extern \"C\" ";
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006707 if (SuperClass->getImplementation())
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006708 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006709 else
6710 Result += "__declspec(dllimport) ";
6711
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006712 Result += "struct _class_t ";
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006713 Result += VarName;
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006714 Result += SuperClass->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006715 Result += ";\n";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006716
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006717 if (metaclass && RootClass != SuperClass) {
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006718 Result += "extern \"C\" ";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006719 if (RootClass->getImplementation())
6720 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006721 else
6722 Result += "__declspec(dllimport) ";
6723
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006724 Result += "struct _class_t ";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006725 Result += VarName;
6726 Result += RootClass->getNameAsString();
6727 Result += ";\n";
6728 }
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006729 }
6730
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006731 Result += "\nextern \"C\" __declspec(dllexport) struct _class_t ";
6732 Result += VarName; Result += CDecl->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006733 Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n";
6734 Result += "\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006735 if (metaclass) {
6736 if (!rootClass) {
6737 Result += "0, // &"; Result += VarName;
6738 Result += RootClass->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006739 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006740 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006741 Result += CDecl->getSuperClass()->getNameAsString();
6742 Result += ",\n\t";
6743 }
6744 else {
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006745 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006746 Result += CDecl->getNameAsString();
6747 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006748 Result += "0, // &OBJC_CLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006749 Result += ",\n\t";
6750 }
6751 }
6752 else {
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006753 Result += "0, // &OBJC_METACLASS_$_";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006754 Result += CDecl->getNameAsString();
6755 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006756 if (!rootClass) {
6757 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006758 Result += CDecl->getSuperClass()->getNameAsString();
6759 Result += ",\n\t";
6760 }
6761 else
6762 Result += "0,\n\t";
6763 }
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006764 Result += "0, // (void *)&_objc_empty_cache,\n\t";
6765 Result += "0, // unused, was (void *)&_objc_empty_vtable,\n\t";
6766 if (metaclass)
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006767 Result += "&_OBJC_METACLASS_RO_$_";
6768 else
6769 Result += "&_OBJC_CLASS_RO_$_";
6770 Result += CDecl->getNameAsString();
6771 Result += ",\n};\n";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006772
6773 // Add static function to initialize some of the meta-data fields.
6774 // avoid doing it twice.
6775 if (metaclass)
6776 return;
6777
6778 const ObjCInterfaceDecl *SuperClass =
6779 rootClass ? CDecl : CDecl->getSuperClass();
6780
6781 Result += "static void OBJC_CLASS_SETUP_$_";
6782 Result += CDecl->getNameAsString();
6783 Result += "(void ) {\n";
6784 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6785 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006786 Result += RootClass->getNameAsString(); Result += ";\n";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006787
6788 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006789 Result += ".superclass = ";
6790 if (rootClass)
6791 Result += "&OBJC_CLASS_$_";
6792 else
6793 Result += "&OBJC_METACLASS_$_";
6794
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006795 Result += SuperClass->getNameAsString(); Result += ";\n";
6796
6797 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6798 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6799
6800 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6801 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
6802 Result += CDecl->getNameAsString(); Result += ";\n";
6803
6804 if (!rootClass) {
6805 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6806 Result += ".superclass = "; Result += "&OBJC_CLASS_$_";
6807 Result += SuperClass->getNameAsString(); Result += ";\n";
6808 }
6809
6810 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6811 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6812 Result += "}\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006813}
6814
Fariborz Jahanian61186122012-02-17 18:40:41 +00006815static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context,
6816 std::string &Result,
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006817 ObjCCategoryDecl *CatDecl,
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006818 ObjCInterfaceDecl *ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00006819 ArrayRef<ObjCMethodDecl *> InstanceMethods,
6820 ArrayRef<ObjCMethodDecl *> ClassMethods,
6821 ArrayRef<ObjCProtocolDecl *> RefedProtocols,
6822 ArrayRef<ObjCPropertyDecl *> ClassProperties) {
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006823 StringRef CatName = CatDecl->getName();
NAKAMURA Takumi20f89392012-03-21 03:21:46 +00006824 StringRef ClassName = ClassDecl->getName();
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00006825 // must declare an extern class object in case this class is not implemented
6826 // in this TU.
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006827 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006828 Result += "extern \"C\" ";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006829 if (ClassDecl->getImplementation())
6830 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006831 else
6832 Result += "__declspec(dllimport) ";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006833
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006834 Result += "struct _class_t ";
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00006835 Result += "OBJC_CLASS_$_"; Result += ClassName;
6836 Result += ";\n";
6837
Fariborz Jahanian61186122012-02-17 18:40:41 +00006838 Result += "\nstatic struct _category_t ";
6839 Result += "_OBJC_$_CATEGORY_";
6840 Result += ClassName; Result += "_$_"; Result += CatName;
6841 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6842 Result += "{\n";
6843 Result += "\t\""; Result += ClassName; Result += "\",\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006844 Result += "\t0, // &"; Result += "OBJC_CLASS_$_"; Result += ClassName;
Fariborz Jahanian61186122012-02-17 18:40:41 +00006845 Result += ",\n";
6846 if (InstanceMethods.size() > 0) {
6847 Result += "\t(const struct _method_list_t *)&";
6848 Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_";
6849 Result += ClassName; Result += "_$_"; Result += CatName;
6850 Result += ",\n";
6851 }
6852 else
6853 Result += "\t0,\n";
6854
6855 if (ClassMethods.size() > 0) {
6856 Result += "\t(const struct _method_list_t *)&";
6857 Result += "_OBJC_$_CATEGORY_CLASS_METHODS_";
6858 Result += ClassName; Result += "_$_"; Result += CatName;
6859 Result += ",\n";
6860 }
6861 else
6862 Result += "\t0,\n";
6863
6864 if (RefedProtocols.size() > 0) {
6865 Result += "\t(const struct _protocol_list_t *)&";
6866 Result += "_OBJC_CATEGORY_PROTOCOLS_$_";
6867 Result += ClassName; Result += "_$_"; Result += CatName;
6868 Result += ",\n";
6869 }
6870 else
6871 Result += "\t0,\n";
6872
6873 if (ClassProperties.size() > 0) {
6874 Result += "\t(const struct _prop_list_t *)&"; Result += "_OBJC_$_PROP_LIST_";
6875 Result += ClassName; Result += "_$_"; Result += CatName;
6876 Result += ",\n";
6877 }
6878 else
6879 Result += "\t0,\n";
6880
6881 Result += "};\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006882
6883 // Add static function to initialize the class pointer in the category structure.
6884 Result += "static void OBJC_CATEGORY_SETUP_$_";
6885 Result += ClassDecl->getNameAsString();
6886 Result += "_$_";
6887 Result += CatName;
6888 Result += "(void ) {\n";
6889 Result += "\t_OBJC_$_CATEGORY_";
6890 Result += ClassDecl->getNameAsString();
6891 Result += "_$_";
6892 Result += CatName;
6893 Result += ".cls = "; Result += "&OBJC_CLASS_$_"; Result += ClassName;
6894 Result += ";\n}\n";
Fariborz Jahanian61186122012-02-17 18:40:41 +00006895}
6896
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006897static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj,
6898 ASTContext *Context, std::string &Result,
6899 ArrayRef<ObjCMethodDecl *> Methods,
6900 StringRef VarName,
6901 StringRef ProtocolName) {
6902 if (Methods.size() == 0)
6903 return;
6904
6905 Result += "\nstatic const char *";
6906 Result += VarName; Result += ProtocolName;
6907 Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6908 Result += "{\n";
6909 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6910 ObjCMethodDecl *MD = Methods[i];
6911 std::string MethodTypeString, QuoteMethodTypeString;
6912 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString, true);
6913 RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString);
6914 Result += "\t\""; Result += QuoteMethodTypeString; Result += "\"";
6915 if (i == e-1)
6916 Result += "\n};\n";
6917 else {
6918 Result += ",\n";
6919 }
6920 }
6921}
6922
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00006923static void Write_IvarOffsetVar(RewriteModernObjC &RewriteObj,
6924 ASTContext *Context,
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00006925 std::string &Result,
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006926 ArrayRef<ObjCIvarDecl *> Ivars,
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006927 ObjCInterfaceDecl *CDecl) {
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006928 // FIXME. visibilty of offset symbols may have to be set; for Darwin
6929 // this is what happens:
6930 /**
6931 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
6932 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
6933 Class->getVisibility() == HiddenVisibility)
6934 Visibility shoud be: HiddenVisibility;
6935 else
6936 Visibility shoud be: DefaultVisibility;
6937 */
6938
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006939 Result += "\n";
6940 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6941 ObjCIvarDecl *IvarDecl = Ivars[i];
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00006942 if (Context->getLangOpts().MicrosoftExt)
6943 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
6944
6945 if (!Context->getLangOpts().MicrosoftExt ||
6946 IvarDecl->getAccessControl() == ObjCIvarDecl::Private ||
Fariborz Jahanian117591f2012-03-10 01:34:42 +00006947 IvarDecl->getAccessControl() == ObjCIvarDecl::Package)
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006948 Result += "extern \"C\" unsigned long int ";
Fariborz Jahaniand1c84d32012-03-10 00:53:02 +00006949 else
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006950 Result += "extern \"C\" __declspec(dllexport) unsigned long int ";
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00006951 if (Ivars[i]->isBitField())
6952 RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
6953 else
6954 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006955 Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))";
6956 Result += " = ";
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00006957 RewriteObj.RewriteIvarOffsetComputation(IvarDecl, Result);
6958 Result += ";\n";
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00006959 if (Ivars[i]->isBitField()) {
6960 // skip over rest of the ivar bitfields.
6961 SKIP_BITFIELDS(i , e, Ivars);
6962 }
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006963 }
6964}
6965
Fariborz Jahanianae932952012-02-10 20:47:10 +00006966static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj,
6967 ASTContext *Context, std::string &Result,
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00006968 ArrayRef<ObjCIvarDecl *> OriginalIvars,
Fariborz Jahanianae932952012-02-10 20:47:10 +00006969 StringRef VarName,
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006970 ObjCInterfaceDecl *CDecl) {
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00006971 if (OriginalIvars.size() > 0) {
6972 Write_IvarOffsetVar(RewriteObj, Context, Result, OriginalIvars, CDecl);
6973 SmallVector<ObjCIvarDecl *, 8> Ivars;
6974 // strip off all but the first ivar bitfield from each group of ivars.
6975 // Such ivars in the ivar list table will be replaced by their grouping struct
6976 // 'ivar'.
6977 for (unsigned i = 0, e = OriginalIvars.size(); i < e; i++) {
6978 if (OriginalIvars[i]->isBitField()) {
6979 Ivars.push_back(OriginalIvars[i]);
6980 // skip over rest of the ivar bitfields.
6981 SKIP_BITFIELDS(i , e, OriginalIvars);
6982 }
6983 else
6984 Ivars.push_back(OriginalIvars[i]);
6985 }
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006986
Fariborz Jahanianae932952012-02-10 20:47:10 +00006987 Result += "\nstatic ";
6988 Write__ivar_list_t_TypeDecl(Result, Ivars.size());
6989 Result += " "; Result += VarName;
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006990 Result += CDecl->getNameAsString();
Fariborz Jahanianae932952012-02-10 20:47:10 +00006991 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6992 Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n";
6993 Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n";
6994 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6995 ObjCIvarDecl *IvarDecl = Ivars[i];
6996 if (i == 0)
6997 Result += "\t{{";
6998 else
6999 Result += "\t {";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00007000 Result += "(unsigned long int *)&";
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00007001 if (Ivars[i]->isBitField())
7002 RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
7003 else
7004 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahaniandb649232012-02-13 20:59:02 +00007005 Result += ", ";
Fariborz Jahanianae932952012-02-10 20:47:10 +00007006
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00007007 Result += "\"";
7008 if (Ivars[i]->isBitField())
7009 RewriteObj.ObjCIvarBitfieldGroupDecl(Ivars[i], Result);
7010 else
7011 Result += IvarDecl->getName();
7012 Result += "\", ";
7013
7014 QualType IVQT = IvarDecl->getType();
7015 if (IvarDecl->isBitField())
7016 IVQT = RewriteObj.GetGroupRecordTypeForObjCIvarBitfield(IvarDecl);
7017
Fariborz Jahanianae932952012-02-10 20:47:10 +00007018 std::string IvarTypeString, QuoteIvarTypeString;
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00007019 Context->getObjCEncodingForType(IVQT, IvarTypeString,
Fariborz Jahanianae932952012-02-10 20:47:10 +00007020 IvarDecl);
7021 RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString);
7022 Result += "\""; Result += QuoteIvarTypeString; Result += "\", ";
7023
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00007024 // FIXME. this alignment represents the host alignment and need be changed to
7025 // represent the target alignment.
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00007026 unsigned Align = Context->getTypeAlign(IVQT)/8;
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00007027 Align = llvm::Log2_32(Align);
Fariborz Jahanianae932952012-02-10 20:47:10 +00007028 Result += llvm::utostr(Align); Result += ", ";
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00007029 CharUnits Size = Context->getTypeSizeInChars(IVQT);
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00007030 Result += llvm::utostr(Size.getQuantity());
Fariborz Jahanianae932952012-02-10 20:47:10 +00007031 if (i == e-1)
7032 Result += "}}\n";
7033 else
7034 Result += "},\n";
7035 }
7036 Result += "};\n";
7037 }
7038}
7039
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007040/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00007041void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl,
7042 std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007043
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007044 // Do not synthesize the protocol more than once.
7045 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
7046 return;
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00007047 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007048
7049 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
7050 PDecl = Def;
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00007051 // Must write out all protocol definitions in current qualifier list,
7052 // and in their nested qualifiers before writing out current definition.
7053 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
7054 E = PDecl->protocol_end(); I != E; ++I)
7055 RewriteObjCProtocolMetaData(*I, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007056
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00007057 // Construct method lists.
7058 std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
7059 std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
7060 for (ObjCProtocolDecl::instmeth_iterator
7061 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
7062 I != E; ++I) {
7063 ObjCMethodDecl *MD = *I;
7064 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
7065 OptInstanceMethods.push_back(MD);
7066 } else {
7067 InstanceMethods.push_back(MD);
7068 }
7069 }
7070
7071 for (ObjCProtocolDecl::classmeth_iterator
7072 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
7073 I != E; ++I) {
7074 ObjCMethodDecl *MD = *I;
7075 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
7076 OptClassMethods.push_back(MD);
7077 } else {
7078 ClassMethods.push_back(MD);
7079 }
7080 }
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00007081 std::vector<ObjCMethodDecl *> AllMethods;
7082 for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++)
7083 AllMethods.push_back(InstanceMethods[i]);
7084 for (unsigned i = 0, e = ClassMethods.size(); i < e; i++)
7085 AllMethods.push_back(ClassMethods[i]);
7086 for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++)
7087 AllMethods.push_back(OptInstanceMethods[i]);
7088 for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++)
7089 AllMethods.push_back(OptClassMethods[i]);
7090
7091 Write__extendedMethodTypes_initializer(*this, Context, Result,
7092 AllMethods,
7093 "_OBJC_PROTOCOL_METHOD_TYPES_",
7094 PDecl->getNameAsString());
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00007095 // Protocol's super protocol list
7096 std::vector<ObjCProtocolDecl *> SuperProtocols;
7097 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
7098 E = PDecl->protocol_end(); I != E; ++I)
7099 SuperProtocols.push_back(*I);
7100
7101 Write_protocol_list_initializer(Context, Result, SuperProtocols,
7102 "_OBJC_PROTOCOL_REFS_",
7103 PDecl->getNameAsString());
7104
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007105 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00007106 "_OBJC_PROTOCOL_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007107 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00007108
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007109 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00007110 "_OBJC_PROTOCOL_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007111 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00007112
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007113 Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00007114 "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007115 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00007116
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007117 Write_method_list_t_initializer(*this, Context, Result, OptClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00007118 "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007119 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00007120
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00007121 // Protocol's property metadata.
7122 std::vector<ObjCPropertyDecl *> ProtocolProperties;
7123 for (ObjCContainerDecl::prop_iterator I = PDecl->prop_begin(),
7124 E = PDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00007125 ProtocolProperties.push_back(*I);
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00007126
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007127 Write_prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00007128 /* Container */0,
7129 "_OBJC_PROTOCOL_PROPERTIES_",
7130 PDecl->getNameAsString());
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00007131
Fariborz Jahanian82848c22012-02-08 00:50:52 +00007132 // Writer out root metadata for current protocol: struct _protocol_t
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007133 Result += "\n";
7134 if (LangOpts.MicrosoftExt)
Fariborz Jahanian8590d862012-04-14 17:13:08 +00007135 Result += "static ";
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00007136 Result += "struct _protocol_t _OBJC_PROTOCOL_";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007137 Result += PDecl->getNameAsString();
Fariborz Jahanian82848c22012-02-08 00:50:52 +00007138 Result += " __attribute__ ((used, section (\"__DATA,__datacoal_nt,coalesced\"))) = {\n";
7139 Result += "\t0,\n"; // id is; is null
7140 Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n";
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00007141 if (SuperProtocols.size() > 0) {
7142 Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_";
7143 Result += PDecl->getNameAsString(); Result += ",\n";
7144 }
7145 else
7146 Result += "\t0,\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00007147 if (InstanceMethods.size() > 0) {
7148 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
7149 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007150 }
7151 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00007152 Result += "\t0,\n";
7153
7154 if (ClassMethods.size() > 0) {
7155 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_";
7156 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007157 }
7158 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00007159 Result += "\t0,\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007160
Fariborz Jahanian82848c22012-02-08 00:50:52 +00007161 if (OptInstanceMethods.size() > 0) {
7162 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_";
7163 Result += PDecl->getNameAsString(); Result += ",\n";
7164 }
7165 else
7166 Result += "\t0,\n";
7167
7168 if (OptClassMethods.size() > 0) {
7169 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_";
7170 Result += PDecl->getNameAsString(); Result += ",\n";
7171 }
7172 else
7173 Result += "\t0,\n";
7174
7175 if (ProtocolProperties.size() > 0) {
7176 Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_";
7177 Result += PDecl->getNameAsString(); Result += ",\n";
7178 }
7179 else
7180 Result += "\t0,\n";
7181
7182 Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n";
7183 Result += "\t0,\n";
7184
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00007185 if (AllMethods.size() > 0) {
7186 Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_";
7187 Result += PDecl->getNameAsString();
7188 Result += "\n};\n";
7189 }
7190 else
7191 Result += "\t0\n};\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00007192
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00007193 if (LangOpts.MicrosoftExt)
Fariborz Jahanian8590d862012-04-14 17:13:08 +00007194 Result += "static ";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00007195 Result += "struct _protocol_t *";
7196 Result += "_OBJC_LABEL_PROTOCOL_$_"; Result += PDecl->getNameAsString();
7197 Result += " = &_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
7198 Result += ";\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00007199
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007200 // Mark this protocol as having been generated.
7201 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()))
7202 llvm_unreachable("protocol already synthesized");
7203
7204}
7205
7206void RewriteModernObjC::RewriteObjCProtocolListMetaData(
7207 const ObjCList<ObjCProtocolDecl> &Protocols,
7208 StringRef prefix, StringRef ClassName,
7209 std::string &Result) {
7210 if (Protocols.empty()) return;
7211
7212 for (unsigned i = 0; i != Protocols.size(); i++)
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00007213 RewriteObjCProtocolMetaData(Protocols[i], Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007214
7215 // Output the top lovel protocol meta-data for the class.
7216 /* struct _objc_protocol_list {
7217 struct _objc_protocol_list *next;
7218 int protocol_count;
7219 struct _objc_protocol *class_protocols[];
7220 }
7221 */
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007222 Result += "\n";
7223 if (LangOpts.MicrosoftExt)
7224 Result += "__declspec(allocate(\".cat_cls_meth$B\")) ";
7225 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007226 Result += "\tstruct _objc_protocol_list *next;\n";
7227 Result += "\tint protocol_count;\n";
7228 Result += "\tstruct _objc_protocol *class_protocols[";
7229 Result += utostr(Protocols.size());
7230 Result += "];\n} _OBJC_";
7231 Result += prefix;
7232 Result += "_PROTOCOLS_";
7233 Result += ClassName;
7234 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
7235 "{\n\t0, ";
7236 Result += utostr(Protocols.size());
7237 Result += "\n";
7238
7239 Result += "\t,{&_OBJC_PROTOCOL_";
7240 Result += Protocols[0]->getNameAsString();
7241 Result += " \n";
7242
7243 for (unsigned i = 1; i != Protocols.size(); i++) {
7244 Result += "\t ,&_OBJC_PROTOCOL_";
7245 Result += Protocols[i]->getNameAsString();
7246 Result += "\n";
7247 }
7248 Result += "\t }\n};\n";
7249}
7250
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00007251/// hasObjCExceptionAttribute - Return true if this class or any super
7252/// class has the __objc_exception__ attribute.
7253/// FIXME. Move this to ASTContext.cpp as it is also used for IRGen.
7254static bool hasObjCExceptionAttribute(ASTContext &Context,
7255 const ObjCInterfaceDecl *OID) {
7256 if (OID->hasAttr<ObjCExceptionAttr>())
7257 return true;
7258 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
7259 return hasObjCExceptionAttribute(Context, Super);
7260 return false;
7261}
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007262
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007263void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
7264 std::string &Result) {
7265 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7266
7267 // Explicitly declared @interface's are already synthesized.
Fariborz Jahanianae932952012-02-10 20:47:10 +00007268 if (CDecl->isImplicitInterfaceDecl())
7269 assert(false &&
7270 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00007271
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00007272 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanianae932952012-02-10 20:47:10 +00007273 SmallVector<ObjCIvarDecl *, 8> IVars;
7274
7275 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7276 IVD; IVD = IVD->getNextIvar()) {
7277 // Ignore unnamed bit-fields.
7278 if (!IVD->getDeclName())
7279 continue;
7280 IVars.push_back(IVD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007281 }
7282
Fariborz Jahanianae932952012-02-10 20:47:10 +00007283 Write__ivar_list_t_initializer(*this, Context, Result, IVars,
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007284 "_OBJC_$_INSTANCE_VARIABLES_",
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00007285 CDecl);
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007286
7287 // Build _objc_method_list for class's instance methods if needed
7288 SmallVector<ObjCMethodDecl *, 32>
7289 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
7290
7291 // If any of our property implementations have associated getters or
7292 // setters, produce metadata for them as well.
7293 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
7294 PropEnd = IDecl->propimpl_end();
7295 Prop != PropEnd; ++Prop) {
David Blaikie262bc182012-04-30 02:36:29 +00007296 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007297 continue;
David Blaikie262bc182012-04-30 02:36:29 +00007298 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007299 continue;
David Blaikie262bc182012-04-30 02:36:29 +00007300 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007301 if (!PD)
7302 continue;
7303 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
Fariborz Jahanian301e2e42012-05-03 22:52:13 +00007304 if (mustSynthesizeSetterGetterMethod(IDecl, PD, true /*getter*/))
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007305 InstanceMethods.push_back(Getter);
7306 if (PD->isReadOnly())
7307 continue;
7308 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
Fariborz Jahanian301e2e42012-05-03 22:52:13 +00007309 if (mustSynthesizeSetterGetterMethod(IDecl, PD, false /*setter*/))
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007310 InstanceMethods.push_back(Setter);
7311 }
7312
7313 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7314 "_OBJC_$_INSTANCE_METHODS_",
7315 IDecl->getNameAsString(), true);
7316
7317 SmallVector<ObjCMethodDecl *, 32>
7318 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
7319
7320 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7321 "_OBJC_$_CLASS_METHODS_",
7322 IDecl->getNameAsString(), true);
Fariborz Jahanian0a525342012-02-14 19:31:35 +00007323
7324 // Protocols referenced in class declaration?
7325 // Protocol's super protocol list
7326 std::vector<ObjCProtocolDecl *> RefedProtocols;
7327 const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols();
7328 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
7329 E = Protocols.end();
7330 I != E; ++I) {
7331 RefedProtocols.push_back(*I);
7332 // Must write out all protocol definitions in current qualifier list,
7333 // and in their nested qualifiers before writing out current definition.
7334 RewriteObjCProtocolMetaData(*I, Result);
7335 }
7336
7337 Write_protocol_list_initializer(Context, Result,
7338 RefedProtocols,
7339 "_OBJC_CLASS_PROTOCOLS_$_",
7340 IDecl->getNameAsString());
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007341
7342 // Protocol's property metadata.
7343 std::vector<ObjCPropertyDecl *> ClassProperties;
7344 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
7345 E = CDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00007346 ClassProperties.push_back(*I);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007347
7348 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahanian2df089d2012-03-22 17:39:35 +00007349 /* Container */IDecl,
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00007350 "_OBJC_$_PROP_LIST_",
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007351 CDecl->getNameAsString());
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007352
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007353
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00007354 // Data for initializing _class_ro_t metaclass meta-data
7355 uint32_t flags = CLS_META;
7356 std::string InstanceSize;
7357 std::string InstanceStart;
7358
7359
7360 bool classIsHidden = CDecl->getVisibility() == HiddenVisibility;
7361 if (classIsHidden)
7362 flags |= OBJC2_CLS_HIDDEN;
7363
7364 if (!CDecl->getSuperClass())
7365 // class is root
7366 flags |= CLS_ROOT;
7367 InstanceSize = "sizeof(struct _class_t)";
7368 InstanceStart = InstanceSize;
7369 Write__class_ro_t_initializer(Context, Result, flags,
7370 InstanceStart, InstanceSize,
7371 ClassMethods,
7372 0,
7373 0,
7374 0,
7375 "_OBJC_METACLASS_RO_$_",
7376 CDecl->getNameAsString());
7377
7378
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007379 // Data for initializing _class_ro_t meta-data
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00007380 flags = CLS;
7381 if (classIsHidden)
7382 flags |= OBJC2_CLS_HIDDEN;
7383
7384 if (hasObjCExceptionAttribute(*Context, CDecl))
7385 flags |= CLS_EXCEPTION;
7386
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007387 if (!CDecl->getSuperClass())
7388 // class is root
7389 flags |= CLS_ROOT;
7390
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00007391 InstanceSize.clear();
7392 InstanceStart.clear();
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007393 if (!ObjCSynthesizedStructs.count(CDecl)) {
7394 InstanceSize = "0";
7395 InstanceStart = "0";
7396 }
7397 else {
7398 InstanceSize = "sizeof(struct ";
7399 InstanceSize += CDecl->getNameAsString();
7400 InstanceSize += "_IMPL)";
7401
7402 ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7403 if (IVD) {
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00007404 RewriteIvarOffsetComputation(IVD, InstanceStart);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007405 }
7406 else
7407 InstanceStart = InstanceSize;
7408 }
7409 Write__class_ro_t_initializer(Context, Result, flags,
7410 InstanceStart, InstanceSize,
7411 InstanceMethods,
7412 RefedProtocols,
7413 IVars,
7414 ClassProperties,
7415 "_OBJC_CLASS_RO_$_",
7416 CDecl->getNameAsString());
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00007417
7418 Write_class_t(Context, Result,
7419 "OBJC_METACLASS_$_",
7420 CDecl, /*metaclass*/true);
7421
7422 Write_class_t(Context, Result,
7423 "OBJC_CLASS_$_",
7424 CDecl, /*metaclass*/false);
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007425
7426 if (ImplementationIsNonLazy(IDecl))
7427 DefinedNonLazyClasses.push_back(CDecl);
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00007428
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007429}
7430
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007431void RewriteModernObjC::RewriteClassSetupInitHook(std::string &Result) {
7432 int ClsDefCount = ClassImplementation.size();
7433 if (!ClsDefCount)
7434 return;
7435 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7436 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7437 Result += "static void *OBJC_CLASS_SETUP[] = {\n";
7438 for (int i = 0; i < ClsDefCount; i++) {
7439 ObjCImplementationDecl *IDecl = ClassImplementation[i];
7440 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7441 Result += "\t(void *)&OBJC_CLASS_SETUP_$_";
7442 Result += CDecl->getName(); Result += ",\n";
7443 }
7444 Result += "};\n";
7445}
7446
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007447void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
7448 int ClsDefCount = ClassImplementation.size();
7449 int CatDefCount = CategoryImplementation.size();
7450
7451 // For each implemented class, write out all its meta data.
7452 for (int i = 0; i < ClsDefCount; i++)
7453 RewriteObjCClassMetaData(ClassImplementation[i], Result);
7454
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007455 RewriteClassSetupInitHook(Result);
7456
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007457 // For each implemented category, write out all its meta data.
7458 for (int i = 0; i < CatDefCount; i++)
7459 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
7460
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007461 RewriteCategorySetupInitHook(Result);
7462
Fariborz Jahaniandf795672012-02-17 00:06:14 +00007463 if (ClsDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007464 if (LangOpts.MicrosoftExt)
7465 Result += "__declspec(allocate(\".objc_classlist$B\")) ";
Fariborz Jahaniandf795672012-02-17 00:06:14 +00007466 Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ [";
7467 Result += llvm::utostr(ClsDefCount); Result += "]";
7468 Result +=
7469 " __attribute__((used, section (\"__DATA, __objc_classlist,"
7470 "regular,no_dead_strip\")))= {\n";
7471 for (int i = 0; i < ClsDefCount; i++) {
7472 Result += "\t&OBJC_CLASS_$_";
7473 Result += ClassImplementation[i]->getNameAsString();
7474 Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007475 }
Fariborz Jahaniandf795672012-02-17 00:06:14 +00007476 Result += "};\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007477
7478 if (!DefinedNonLazyClasses.empty()) {
7479 if (LangOpts.MicrosoftExt)
7480 Result += "__declspec(allocate(\".objc_nlclslist$B\")) \n";
7481 Result += "static struct _class_t *_OBJC_LABEL_NONLAZY_CLASS_$[] = {\n\t";
7482 for (unsigned i = 0, e = DefinedNonLazyClasses.size(); i < e; i++) {
7483 Result += "\t&OBJC_CLASS_$_"; Result += DefinedNonLazyClasses[i]->getNameAsString();
7484 Result += ",\n";
7485 }
7486 Result += "};\n";
7487 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007488 }
Fariborz Jahanian61186122012-02-17 18:40:41 +00007489
7490 if (CatDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007491 if (LangOpts.MicrosoftExt)
7492 Result += "__declspec(allocate(\".objc_catlist$B\")) ";
Fariborz Jahanian61186122012-02-17 18:40:41 +00007493 Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [";
7494 Result += llvm::utostr(CatDefCount); Result += "]";
7495 Result +=
7496 " __attribute__((used, section (\"__DATA, __objc_catlist,"
7497 "regular,no_dead_strip\")))= {\n";
7498 for (int i = 0; i < CatDefCount; i++) {
7499 Result += "\t&_OBJC_$_CATEGORY_";
7500 Result +=
7501 CategoryImplementation[i]->getClassInterface()->getNameAsString();
7502 Result += "_$_";
7503 Result += CategoryImplementation[i]->getNameAsString();
7504 Result += ",\n";
7505 }
7506 Result += "};\n";
7507 }
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007508
7509 if (!DefinedNonLazyCategories.empty()) {
7510 if (LangOpts.MicrosoftExt)
7511 Result += "__declspec(allocate(\".objc_nlcatlist$B\")) \n";
7512 Result += "static struct _category_t *_OBJC_LABEL_NONLAZY_CATEGORY_$[] = {\n\t";
7513 for (unsigned i = 0, e = DefinedNonLazyCategories.size(); i < e; i++) {
7514 Result += "\t&_OBJC_$_CATEGORY_";
7515 Result +=
7516 DefinedNonLazyCategories[i]->getClassInterface()->getNameAsString();
7517 Result += "_$_";
7518 Result += DefinedNonLazyCategories[i]->getNameAsString();
7519 Result += ",\n";
7520 }
7521 Result += "};\n";
7522 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007523}
7524
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00007525void RewriteModernObjC::WriteImageInfo(std::string &Result) {
7526 if (LangOpts.MicrosoftExt)
7527 Result += "__declspec(allocate(\".objc_imageinfo$B\")) \n";
7528
7529 Result += "static struct IMAGE_INFO { unsigned version; unsigned flag; } ";
7530 // version 0, ObjCABI is 2
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00007531 Result += "_OBJC_IMAGE_INFO = { 0, 2 };\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00007532}
7533
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007534/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
7535/// implementation.
7536void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
7537 std::string &Result) {
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00007538 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007539 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7540 // Find category declaration for this implementation.
Douglas Gregord3297242013-01-16 23:00:23 +00007541 ObjCCategoryDecl *CDecl
7542 = ClassDecl->FindCategoryDeclaration(IDecl->getIdentifier());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007543
7544 std::string FullCategoryName = ClassDecl->getNameAsString();
Fariborz Jahanian61186122012-02-17 18:40:41 +00007545 FullCategoryName += "_$_";
7546 FullCategoryName += CDecl->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007547
7548 // Build _objc_method_list for class's instance methods if needed
7549 SmallVector<ObjCMethodDecl *, 32>
7550 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
7551
7552 // If any of our property implementations have associated getters or
7553 // setters, produce metadata for them as well.
7554 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
7555 PropEnd = IDecl->propimpl_end();
7556 Prop != PropEnd; ++Prop) {
David Blaikie262bc182012-04-30 02:36:29 +00007557 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007558 continue;
David Blaikie262bc182012-04-30 02:36:29 +00007559 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007560 continue;
David Blaikie262bc182012-04-30 02:36:29 +00007561 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007562 if (!PD)
7563 continue;
7564 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
7565 InstanceMethods.push_back(Getter);
7566 if (PD->isReadOnly())
7567 continue;
7568 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
7569 InstanceMethods.push_back(Setter);
7570 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007571
Fariborz Jahanian61186122012-02-17 18:40:41 +00007572 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7573 "_OBJC_$_CATEGORY_INSTANCE_METHODS_",
7574 FullCategoryName, true);
7575
7576 SmallVector<ObjCMethodDecl *, 32>
7577 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
7578
7579 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7580 "_OBJC_$_CATEGORY_CLASS_METHODS_",
7581 FullCategoryName, true);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007582
7583 // Protocols referenced in class declaration?
Fariborz Jahanian61186122012-02-17 18:40:41 +00007584 // Protocol's super protocol list
7585 std::vector<ObjCProtocolDecl *> RefedProtocols;
Argyrios Kyrtzidisa5f44412012-03-13 01:09:41 +00007586 for (ObjCInterfaceDecl::protocol_iterator I = CDecl->protocol_begin(),
7587 E = CDecl->protocol_end();
7588
7589 I != E; ++I) {
Fariborz Jahanian61186122012-02-17 18:40:41 +00007590 RefedProtocols.push_back(*I);
7591 // Must write out all protocol definitions in current qualifier list,
7592 // and in their nested qualifiers before writing out current definition.
7593 RewriteObjCProtocolMetaData(*I, Result);
7594 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007595
Fariborz Jahanian61186122012-02-17 18:40:41 +00007596 Write_protocol_list_initializer(Context, Result,
7597 RefedProtocols,
7598 "_OBJC_CATEGORY_PROTOCOLS_$_",
7599 FullCategoryName);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007600
Fariborz Jahanian61186122012-02-17 18:40:41 +00007601 // Protocol's property metadata.
7602 std::vector<ObjCPropertyDecl *> ClassProperties;
7603 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
7604 E = CDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00007605 ClassProperties.push_back(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007606
Fariborz Jahanian61186122012-02-17 18:40:41 +00007607 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahanianebfa2722012-05-03 23:19:33 +00007608 /* Container */IDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00007609 "_OBJC_$_PROP_LIST_",
7610 FullCategoryName);
7611
7612 Write_category_t(*this, Context, Result,
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007613 CDecl,
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007614 ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00007615 InstanceMethods,
7616 ClassMethods,
7617 RefedProtocols,
7618 ClassProperties);
7619
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007620 // Determine if this category is also "non-lazy".
7621 if (ImplementationIsNonLazy(IDecl))
7622 DefinedNonLazyCategories.push_back(CDecl);
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007623
7624}
7625
7626void RewriteModernObjC::RewriteCategorySetupInitHook(std::string &Result) {
7627 int CatDefCount = CategoryImplementation.size();
7628 if (!CatDefCount)
7629 return;
7630 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7631 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7632 Result += "static void *OBJC_CATEGORY_SETUP[] = {\n";
7633 for (int i = 0; i < CatDefCount; i++) {
7634 ObjCCategoryImplDecl *IDecl = CategoryImplementation[i];
7635 ObjCCategoryDecl *CatDecl= IDecl->getCategoryDecl();
7636 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7637 Result += "\t(void *)&OBJC_CATEGORY_SETUP_$_";
7638 Result += ClassDecl->getName();
7639 Result += "_$_";
7640 Result += CatDecl->getName();
7641 Result += ",\n";
7642 }
7643 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007644}
7645
7646// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
7647/// class methods.
7648template<typename MethodIterator>
7649void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
7650 MethodIterator MethodEnd,
7651 bool IsInstanceMethod,
7652 StringRef prefix,
7653 StringRef ClassName,
7654 std::string &Result) {
7655 if (MethodBegin == MethodEnd) return;
7656
7657 if (!objc_impl_method) {
7658 /* struct _objc_method {
7659 SEL _cmd;
7660 char *method_types;
7661 void *_imp;
7662 }
7663 */
7664 Result += "\nstruct _objc_method {\n";
7665 Result += "\tSEL _cmd;\n";
7666 Result += "\tchar *method_types;\n";
7667 Result += "\tvoid *_imp;\n";
7668 Result += "};\n";
7669
7670 objc_impl_method = true;
7671 }
7672
7673 // Build _objc_method_list for class's methods if needed
7674
7675 /* struct {
7676 struct _objc_method_list *next_method;
7677 int method_count;
7678 struct _objc_method method_list[];
7679 }
7680 */
7681 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007682 Result += "\n";
7683 if (LangOpts.MicrosoftExt) {
7684 if (IsInstanceMethod)
7685 Result += "__declspec(allocate(\".inst_meth$B\")) ";
7686 else
7687 Result += "__declspec(allocate(\".cls_meth$B\")) ";
7688 }
7689 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007690 Result += "\tstruct _objc_method_list *next_method;\n";
7691 Result += "\tint method_count;\n";
7692 Result += "\tstruct _objc_method method_list[";
7693 Result += utostr(NumMethods);
7694 Result += "];\n} _OBJC_";
7695 Result += prefix;
7696 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
7697 Result += "_METHODS_";
7698 Result += ClassName;
7699 Result += " __attribute__ ((used, section (\"__OBJC, __";
7700 Result += IsInstanceMethod ? "inst" : "cls";
7701 Result += "_meth\")))= ";
7702 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
7703
7704 Result += "\t,{{(SEL)\"";
7705 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7706 std::string MethodTypeString;
7707 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7708 Result += "\", \"";
7709 Result += MethodTypeString;
7710 Result += "\", (void *)";
7711 Result += MethodInternalNames[*MethodBegin];
7712 Result += "}\n";
7713 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
7714 Result += "\t ,{(SEL)\"";
7715 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7716 std::string MethodTypeString;
7717 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7718 Result += "\", \"";
7719 Result += MethodTypeString;
7720 Result += "\", (void *)";
7721 Result += MethodInternalNames[*MethodBegin];
7722 Result += "}\n";
7723 }
7724 Result += "\t }\n};\n";
7725}
7726
7727Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
7728 SourceRange OldRange = IV->getSourceRange();
7729 Expr *BaseExpr = IV->getBase();
7730
7731 // Rewrite the base, but without actually doing replaces.
7732 {
7733 DisableReplaceStmtScope S(*this);
7734 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
7735 IV->setBase(BaseExpr);
7736 }
7737
7738 ObjCIvarDecl *D = IV->getDecl();
7739
7740 Expr *Replacement = IV;
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007741
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007742 if (BaseExpr->getType()->isObjCObjectPointerType()) {
7743 const ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +00007744 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007745 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
7746 // lookup which class implements the instance variable.
7747 ObjCInterfaceDecl *clsDeclared = 0;
7748 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
7749 clsDeclared);
7750 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
7751
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007752 // Build name of symbol holding ivar offset.
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00007753 std::string IvarOffsetName;
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00007754 if (D->isBitField())
7755 ObjCIvarBitfieldGroupOffset(D, IvarOffsetName);
7756 else
7757 WriteInternalIvarName(clsDeclared, D, IvarOffsetName);
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00007758
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00007759 ReferencedIvars[clsDeclared].insert(D);
7760
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007761 // cast offset to "char *".
7762 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context,
7763 Context->getPointerType(Context->CharTy),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007764 CK_BitCast,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007765 BaseExpr);
7766 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
7767 SourceLocation(), &Context->Idents.get(IvarOffsetName),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00007768 Context->UnsignedLongTy, 0, SC_Extern);
John McCallf4b88a42012-03-10 09:33:50 +00007769 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false,
7770 Context->UnsignedLongTy, VK_LValue,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007771 SourceLocation());
7772 BinaryOperator *addExpr =
7773 new (Context) BinaryOperator(castExpr, DRE, BO_Add,
7774 Context->getPointerType(Context->CharTy),
Lang Hamesbe9af122012-10-02 04:45:10 +00007775 VK_RValue, OK_Ordinary, SourceLocation(), false);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007776 // Don't forget the parens to enforce the proper binding.
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007777 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(),
7778 SourceLocation(),
7779 addExpr);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00007780 QualType IvarT = D->getType();
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00007781 if (D->isBitField())
7782 IvarT = GetGroupRecordTypeForObjCIvarBitfield(D);
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007783
Fariborz Jahanianf5eac482012-05-02 17:34:59 +00007784 if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007785 RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00007786 RD = RD->getDefinition();
7787 if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007788 // decltype(((Foo_IMPL*)0)->bar) *
Fariborz Jahanianf5eac482012-05-02 17:34:59 +00007789 ObjCContainerDecl *CDecl =
7790 dyn_cast<ObjCContainerDecl>(D->getDeclContext());
7791 // ivar in class extensions requires special treatment.
7792 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
7793 CDecl = CatDecl->getClassInterface();
7794 std::string RecName = CDecl->getName();
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007795 RecName += "_IMPL";
7796 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
7797 SourceLocation(), SourceLocation(),
7798 &Context->Idents.get(RecName.c_str()));
7799 QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
7800 unsigned UnsignedIntSize =
7801 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
7802 Expr *Zero = IntegerLiteral::Create(*Context,
7803 llvm::APInt(UnsignedIntSize, 0),
7804 Context->UnsignedIntTy, SourceLocation());
7805 Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
7806 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
7807 Zero);
7808 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
7809 SourceLocation(),
7810 &Context->Idents.get(D->getNameAsString()),
7811 IvarT, 0,
7812 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00007813 ICIS_NoInit);
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007814 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
7815 FD->getType(), VK_LValue,
7816 OK_Ordinary);
7817 IvarT = Context->getDecltypeType(ME, ME->getType());
7818 }
7819 }
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00007820 convertObjCTypeToCStyleType(IvarT);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00007821 QualType castT = Context->getPointerType(IvarT);
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007822
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007823 castExpr = NoTypeInfoCStyleCastExpr(Context,
7824 castT,
7825 CK_BitCast,
7826 PE);
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007827
7828
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00007829 Expr *Exp = new (Context) UnaryOperator(castExpr, UO_Deref, IvarT,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007830 VK_LValue, OK_Ordinary,
7831 SourceLocation());
7832 PE = new (Context) ParenExpr(OldRange.getBegin(),
7833 OldRange.getEnd(),
7834 Exp);
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00007835
7836 if (D->isBitField()) {
7837 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
7838 SourceLocation(),
7839 &Context->Idents.get(D->getNameAsString()),
7840 D->getType(), 0,
7841 /*BitWidth=*/D->getBitWidth(),
7842 /*Mutable=*/true,
7843 ICIS_NoInit);
7844 MemberExpr *ME = new (Context) MemberExpr(PE, /*isArrow*/false, FD, SourceLocation(),
7845 FD->getType(), VK_LValue,
7846 OK_Ordinary);
7847 Replacement = ME;
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007848
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00007849 }
7850 else
7851 Replacement = PE;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007852 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007853
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007854 ReplaceStmtWithRange(IV, Replacement, OldRange);
7855 return Replacement;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007856}