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