Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/clang/lib/ARCMigrate/TransUnbridgedCasts.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- TransUnbridgedCasts.cpp - Transformations to ARC mode ------------===//
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
// rewriteUnbridgedCasts:
10
//
11
// A cast of non-objc pointer to an objc one is checked. If the non-objc pointer
12
// is from a file-level variable, __bridge cast is used to convert it.
13
// For the result of a function call that we know is +1/+0,
14
// __bridge/CFBridgingRelease is used.
15
//
16
//  NSString *str = (NSString *)kUTTypePlainText;
17
//  str = b ? kUTTypeRTF : kUTTypePlainText;
18
//  NSString *_uuidString = (NSString *)CFUUIDCreateString(kCFAllocatorDefault,
19
//                                                         _uuid);
20
// ---->
21
//  NSString *str = (__bridge NSString *)kUTTypePlainText;
22
//  str = (__bridge NSString *)(b ? kUTTypeRTF : kUTTypePlainText);
23
// NSString *_uuidString = (NSString *)
24
//            CFBridgingRelease(CFUUIDCreateString(kCFAllocatorDefault, _uuid));
25
//
26
// For a C pointer to ObjC, for casting 'self', __bridge is used.
27
//
28
//  CFStringRef str = (CFStringRef)self;
29
// ---->
30
//  CFStringRef str = (__bridge CFStringRef)self;
31
//
32
// Uses of Block_copy/Block_release macros are rewritten:
33
//
34
//  c = Block_copy(b);
35
//  Block_release(c);
36
// ---->
37
//  c = [b copy];
38
//  <removed>
39
//
40
//===----------------------------------------------------------------------===//
41
42
#include "Transforms.h"
43
#include "Internals.h"
44
#include "clang/AST/ASTContext.h"
45
#include "clang/AST/Attr.h"
46
#include "clang/AST/ParentMap.h"
47
#include "clang/Analysis/DomainSpecific/CocoaConventions.h"
48
#include "clang/Basic/SourceManager.h"
49
#include "clang/Lex/Lexer.h"
50
#include "clang/Sema/SemaDiagnostic.h"
51
#include "llvm/ADT/SmallString.h"
52
53
using namespace clang;
54
using namespace arcmt;
55
using namespace trans;
56
57
namespace {
58
59
class UnbridgedCastRewriter : public RecursiveASTVisitor<UnbridgedCastRewriter>{
60
  MigrationPass &Pass;
61
  IdentifierInfo *SelfII;
62
  std::unique_ptr<ParentMap> StmtMap;
63
  Decl *ParentD;
64
  Stmt *Body;
65
  mutable std::unique_ptr<ExprSet> Removables;
66
67
public:
68
  UnbridgedCastRewriter(MigrationPass &pass)
69
425
    : Pass(pass), ParentD(nullptr), Body(nullptr) {
70
425
    SelfII = &Pass.Ctx.Idents.get("self");
71
425
  }
72
73
425
  void transformBody(Stmt *body, Decl *ParentD) {
74
425
    this->ParentD = ParentD;
75
425
    Body = body;
76
425
    StmtMap.reset(new ParentMap(body));
77
425
    TraverseStmt(body);
78
425
  }
79
80
22
  bool TraverseBlockDecl(BlockDecl *D) {
81
22
    // ParentMap does not enter into a BlockDecl to record its stmts, so use a
82
22
    // new UnbridgedCastRewriter to handle the block.
83
22
    UnbridgedCastRewriter(Pass).transformBody(D->getBody(), D);
84
22
    return true;
85
22
  }
86
87
1.87k
  bool VisitCastExpr(CastExpr *E) {
88
1.87k
    if (E->getCastKind() != CK_CPointerToObjCPointerCast &&
89
1.87k
        
E->getCastKind() != CK_BitCast1.79k
&&
90
1.87k
        
E->getCastKind() != CK_AnyPointerToBlockPointerCast1.57k
)
91
1.56k
      return true;
92
307
93
307
    QualType castType = E->getType();
94
307
    Expr *castExpr = E->getSubExpr();
95
307
    QualType castExprType = castExpr->getType();
96
307
97
307
    if (castType->isObjCRetainableType() == castExprType->isObjCRetainableType())
98
127
      return true;
99
180
100
180
    bool exprRetainable = castExprType->isObjCIndirectLifetimeType();
101
180
    bool castRetainable = castType->isObjCIndirectLifetimeType();
102
180
    if (exprRetainable == castRetainable) 
return true2
;
103
178
104
178
    if (castExpr->isNullPointerConstant(Pass.Ctx,
105
178
                                        Expr::NPC_ValueDependentIsNull))
106
0
      return true;
107
178
108
178
    SourceLocation loc = castExpr->getExprLoc();
109
178
    if (loc.isValid() && Pass.Ctx.getSourceManager().isInSystemHeader(loc))
110
0
      return true;
111
178
112
178
    if (castType->isObjCRetainableType())
113
85
      transformNonObjCToObjCCast(E);
114
93
    else
115
93
      transformObjCToNonObjCCast(E);
116
178
117
178
    return true;
118
178
  }
119
120
private:
121
85
  void transformNonObjCToObjCCast(CastExpr *E) {
122
85
    if (!E) 
return0
;
123
85
124
85
    // Global vars are assumed that are cast as unretained.
125
85
    if (isGlobalVar(E))
126
14
      if (E->getSubExpr()->getType()->isPointerType()) {
127
14
        castToObjCObject(E, /*retained=*/false);
128
14
        return;
129
14
      }
130
71
131
71
    // If the cast is directly over the result of a Core Foundation function
132
71
    // try to figure out whether it should be cast as retained or unretained.
133
71
    Expr *inner = E->IgnoreParenCasts();
134
71
    if (CallExpr *callE = dyn_cast<CallExpr>(inner)) {
135
17
      if (FunctionDecl *FD = callE->getDirectCallee()) {
136
17
        if (FD->hasAttr<CFReturnsRetainedAttr>()) {
137
0
          castToObjCObject(E, /*retained=*/true);
138
0
          return;
139
0
        }
140
17
        if (FD->hasAttr<CFReturnsNotRetainedAttr>()) {
141
0
          castToObjCObject(E, /*retained=*/false);
142
0
          return;
143
0
        }
144
17
        if (FD->isGlobal() &&
145
17
            FD->getIdentifier() &&
146
17
            ento::cocoa::isRefType(E->getSubExpr()->getType(), "CF",
147
17
                                   FD->getIdentifier()->getName())) {
148
13
          StringRef fname = FD->getIdentifier()->getName();
149
13
          if (fname.endswith("Retain") ||
150
13
              
fname.find("Create") != StringRef::npos4
||
151
13
              
fname.find("Copy") != StringRef::npos0
) {
152
13
            // Do not migrate to couple of bridge transfer casts which
153
13
            // cancel each other out. Leave it unchanged so error gets user
154
13
            // attention instead.
155
13
            if (FD->getName() == "CFRetain" &&
156
13
                
FD->getNumParams() == 19
&&
157
13
                
FD->getParent()->isTranslationUnit()9
&&
158
13
                
FD->isExternallyVisible()9
) {
159
9
              Expr *Arg = callE->getArg(0);
160
9
              if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) {
161
8
                const Expr *sub = ICE->getSubExpr();
162
8
                QualType T = sub->getType();
163
8
                if (T->isObjCObjectPointerType())
164
3
                  return;
165
10
              }
166
9
            }
167
10
            castToObjCObject(E, /*retained=*/true);
168
10
            return;
169
10
          }
170
0
171
0
          if (fname.find("Get") != StringRef::npos) {
172
0
            castToObjCObject(E, /*retained=*/false);
173
0
            return;
174
0
          }
175
58
        }
176
17
      }
177
17
    }
178
58
179
58
    // If returning an ivar or a member of an ivar from a +0 method, use
180
58
    // a __bridge cast.
181
58
    Expr *base = inner->IgnoreParenImpCasts();
182
61
    while (isa<MemberExpr>(base))
183
3
      base = cast<MemberExpr>(base)->getBase()->IgnoreParenImpCasts();
184
58
    if (isa<ObjCIvarRefExpr>(base) &&
185
58
        
isa<ReturnStmt>(StmtMap->getParentIgnoreParenCasts(E))9
) {
186
7
      if (ObjCMethodDecl *method = dyn_cast_or_null<ObjCMethodDecl>(ParentD)) {
187
7
        if (!method->hasAttr<NSReturnsRetainedAttr>()) {
188
6
          castToObjCObject(E, /*retained=*/false);
189
6
          return;
190
6
        }
191
7
      }
192
7
    }
193
58
  }
194
195
30
  void castToObjCObject(CastExpr *E, bool retained) {
196
30
    rewriteToBridgedCast(E, retained ? 
OBC_BridgeTransfer10
:
OBC_Bridge20
);
197
30
  }
198
199
57
  void rewriteToBridgedCast(CastExpr *E, ObjCBridgeCastKind Kind) {
200
57
    Transaction Trans(Pass.TA);
201
57
    rewriteToBridgedCast(E, Kind, Trans);
202
57
  }
203
204
  void rewriteToBridgedCast(CastExpr *E, ObjCBridgeCastKind Kind,
205
67
                            Transaction &Trans) {
206
67
    TransformActions &TA = Pass.TA;
207
67
208
67
    // We will remove the compiler diagnostic.
209
67
    if (!TA.hasDiagnostic(diag::err_arc_mismatched_cast,
210
67
                          diag::err_arc_cast_requires_bridge,
211
67
                          E->getBeginLoc())) {
212
8
      Trans.abort();
213
8
      return;
214
8
    }
215
59
216
59
    StringRef bridge;
217
59
    switch(Kind) {
218
59
    case OBC_Bridge:
219
23
      bridge = "__bridge "; break;
220
59
    case OBC_BridgeTransfer:
221
10
      bridge = "__bridge_transfer "; break;
222
59
    case OBC_BridgeRetained:
223
26
      bridge = "__bridge_retained "; break;
224
59
    }
225
59
226
59
    TA.clearDiagnostic(diag::err_arc_mismatched_cast,
227
59
                       diag::err_arc_cast_requires_bridge, E->getBeginLoc());
228
59
    if (Kind == OBC_Bridge || 
!Pass.CFBridgingFunctionsDefined()36
) {
229
23
      if (CStyleCastExpr *CCE = dyn_cast<CStyleCastExpr>(E)) {
230
9
        TA.insertAfterToken(CCE->getLParenLoc(), bridge);
231
14
      } else {
232
14
        SourceLocation insertLoc = E->getSubExpr()->getBeginLoc();
233
14
        SmallString<128> newCast;
234
14
        newCast += '(';
235
14
        newCast += bridge;
236
14
        newCast += E->getType().getAsString(Pass.Ctx.getPrintingPolicy());
237
14
        newCast += ')';
238
14
239
14
        if (isa<ParenExpr>(E->getSubExpr())) {
240
0
          TA.insert(insertLoc, newCast.str());
241
14
        } else {
242
14
          newCast += '(';
243
14
          TA.insert(insertLoc, newCast.str());
244
14
          TA.insertAfterToken(E->getEndLoc(), ")");
245
14
        }
246
14
      }
247
36
    } else {
248
36
      assert(Kind == OBC_BridgeTransfer || Kind == OBC_BridgeRetained);
249
36
      SmallString<32> BridgeCall;
250
36
251
36
      Expr *WrapE = E->getSubExpr();
252
36
      SourceLocation InsertLoc = WrapE->getBeginLoc();
253
36
254
36
      SourceManager &SM = Pass.Ctx.getSourceManager();
255
36
      char PrevChar = *SM.getCharacterData(InsertLoc.getLocWithOffset(-1));
256
36
      if (Lexer::isIdentifierBodyChar(PrevChar, Pass.Ctx.getLangOpts()))
257
0
        BridgeCall += ' ';
258
36
259
36
      if (Kind == OBC_BridgeTransfer)
260
10
        BridgeCall += "CFBridgingRelease";
261
26
      else
262
26
        BridgeCall += "CFBridgingRetain";
263
36
264
36
      if (isa<ParenExpr>(WrapE)) {
265
0
        TA.insert(InsertLoc, BridgeCall);
266
36
      } else {
267
36
        BridgeCall += '(';
268
36
        TA.insert(InsertLoc, BridgeCall);
269
36
        TA.insertAfterToken(WrapE->getEndLoc(), ")");
270
36
      }
271
36
    }
272
59
  }
273
274
10
  void rewriteCastForCFRetain(CastExpr *castE, CallExpr *callE) {
275
10
    Transaction Trans(Pass.TA);
276
10
    Pass.TA.replace(callE->getSourceRange(), callE->getArg(0)->getSourceRange());
277
10
    rewriteToBridgedCast(castE, OBC_BridgeRetained, Trans);
278
10
  }
279
280
8
  void getBlockMacroRanges(CastExpr *E, SourceRange &Outer, SourceRange &Inner) {
281
8
    SourceManager &SM = Pass.Ctx.getSourceManager();
282
8
    SourceLocation Loc = E->getExprLoc();
283
8
    assert(Loc.isMacroID());
284
8
    CharSourceRange MacroRange = SM.getImmediateExpansionRange(Loc);
285
8
    SourceRange SubRange = E->getSubExpr()->IgnoreParenImpCasts()->getSourceRange();
286
8
    SourceLocation InnerBegin = SM.getImmediateMacroCallerLoc(SubRange.getBegin());
287
8
    SourceLocation InnerEnd = SM.getImmediateMacroCallerLoc(SubRange.getEnd());
288
8
289
8
    Outer = MacroRange.getAsRange();
290
8
    Inner = SourceRange(InnerBegin, InnerEnd);
291
8
  }
292
293
4
  void rewriteBlockCopyMacro(CastExpr *E) {
294
4
    SourceRange OuterRange, InnerRange;
295
4
    getBlockMacroRanges(E, OuterRange, InnerRange);
296
4
297
4
    Transaction Trans(Pass.TA);
298
4
    Pass.TA.replace(OuterRange, InnerRange);
299
4
    Pass.TA.insert(InnerRange.getBegin(), "[");
300
4
    Pass.TA.insertAfterToken(InnerRange.getEnd(), " copy]");
301
4
    Pass.TA.clearDiagnostic(diag::err_arc_mismatched_cast,
302
4
                            diag::err_arc_cast_requires_bridge,
303
4
                            OuterRange);
304
4
  }
305
306
4
  void removeBlockReleaseMacro(CastExpr *E) {
307
4
    SourceRange OuterRange, InnerRange;
308
4
    getBlockMacroRanges(E, OuterRange, InnerRange);
309
4
310
4
    Transaction Trans(Pass.TA);
311
4
    Pass.TA.clearDiagnostic(diag::err_arc_mismatched_cast,
312
4
                            diag::err_arc_cast_requires_bridge,
313
4
                            OuterRange);
314
4
    if (!hasSideEffects(E, Pass.Ctx)) {
315
4
      if (tryRemoving(cast<Expr>(StmtMap->getParentIgnoreParenCasts(E))))
316
4
        return;
317
0
    }
318
0
    Pass.TA.replace(OuterRange, InnerRange);
319
0
  }
320
321
4
  bool tryRemoving(Expr *E) const {
322
4
    if (!Removables) {
323
4
      Removables.reset(new ExprSet);
324
4
      collectRemovables(Body, *Removables);
325
4
    }
326
4
327
4
    if (Removables->count(E)) {
328
4
      Pass.TA.removeStmt(E);
329
4
      return true;
330
4
    }
331
0
332
0
    return false;
333
0
  }
334
335
93
  void transformObjCToNonObjCCast(CastExpr *E) {
336
93
    SourceLocation CastLoc = E->getExprLoc();
337
93
    if (CastLoc.isMacroID()) {
338
8
      StringRef MacroName = Lexer::getImmediateMacroName(CastLoc,
339
8
                                                    Pass.Ctx.getSourceManager(),
340
8
                                                    Pass.Ctx.getLangOpts());
341
8
      if (MacroName == "Block_copy") {
342
4
        rewriteBlockCopyMacro(E);
343
4
        return;
344
4
      }
345
4
      if (MacroName == "Block_release") {
346
4
        removeBlockReleaseMacro(E);
347
4
        return;
348
4
      }
349
85
    }
350
85
351
85
    if (isSelf(E->getSubExpr()))
352
4
      return rewriteToBridgedCast(E, OBC_Bridge);
353
81
354
81
    CallExpr *callE;
355
81
    if (isPassedToCFRetain(E, callE))
356
10
      return rewriteCastForCFRetain(E, callE);
357
71
358
71
    ObjCMethodFamily family = getFamilyOfMessage(E->getSubExpr());
359
71
    if (family == OMF_retain)
360
4
      return rewriteToBridgedCast(E, OBC_BridgeRetained);
361
67
362
67
    if (family == OMF_autorelease || 
family == OMF_release66
) {
363
1
      std::string err = "it is not safe to cast to '";
364
1
      err += E->getType().getAsString(Pass.Ctx.getPrintingPolicy());
365
1
      err += "' the result of '";
366
1
      err += family == OMF_autorelease ? "autorelease" : 
"release"0
;
367
1
      err += "' message; a __bridge cast may result in a pointer to a "
368
1
          "destroyed object and a __bridge_retained may leak the object";
369
1
      Pass.TA.reportError(err, E->getBeginLoc(),
370
1
                          E->getSubExpr()->getSourceRange());
371
1
      Stmt *parent = E;
372
1
      do {
373
1
        parent = StmtMap->getParentIgnoreParenImpCasts(parent);
374
1
      } while (parent && isa<FullExpr>(parent));
375
1
376
1
      if (ReturnStmt *retS = dyn_cast_or_null<ReturnStmt>(parent)) {
377
1
        std::string note = "remove the cast and change return type of function "
378
1
            "to '";
379
1
        note += E->getSubExpr()->getType().getAsString(Pass.Ctx.getPrintingPolicy());
380
1
        note += "' to have the object automatically autoreleased";
381
1
        Pass.TA.reportNote(note, retS->getBeginLoc());
382
1
      }
383
1
    }
384
67
385
67
    Expr *subExpr = E->getSubExpr();
386
67
387
67
    // Look through pseudo-object expressions.
388
67
    if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(subExpr)) {
389
2
      subExpr = pseudo->getResultExpr();
390
2
      assert(subExpr && "no result for pseudo-object of non-void type?");
391
2
    }
392
67
393
67
    if (ImplicitCastExpr *implCE = dyn_cast<ImplicitCastExpr>(subExpr)) {
394
67
      if (implCE->getCastKind() == CK_ARCConsumeObject)
395
8
        return rewriteToBridgedCast(E, OBC_BridgeRetained);
396
59
      if (implCE->getCastKind() == CK_ARCReclaimReturnedObject)
397
7
        return rewriteToBridgedCast(E, OBC_Bridge);
398
52
    }
399
52
400
52
    bool isConsumed = false;
401
52
    if (isPassedToCParamWithKnownOwnership(E, isConsumed))
402
4
      return rewriteToBridgedCast(E, isConsumed ? OBC_BridgeRetained
403
4
                                                : 
OBC_Bridge0
);
404
52
  }
405
406
71
  static ObjCMethodFamily getFamilyOfMessage(Expr *E) {
407
71
    E = E->IgnoreParenCasts();
408
71
    if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E))
409
17
      return ME->getMethodFamily();
410
54
411
54
    return OMF_None;
412
54
  }
413
414
81
  bool isPassedToCFRetain(Expr *E, CallExpr *&callE) const {
415
81
    if ((callE = dyn_cast_or_null<CallExpr>(
416
81
                                     StmtMap->getParentIgnoreParenImpCasts(E))))
417
16
      if (FunctionDecl *
418
16
            FD = dyn_cast_or_null<FunctionDecl>(callE->getCalleeDecl()))
419
16
        if (FD->getName() == "CFRetain" && 
FD->getNumParams() == 110
&&
420
16
            
FD->getParent()->isTranslationUnit()10
&&
421
16
            
FD->isExternallyVisible()10
)
422
10
          return true;
423
71
424
71
    return false;
425
71
  }
426
427
52
  bool isPassedToCParamWithKnownOwnership(Expr *E, bool &isConsumed) const {
428
52
    if (CallExpr *callE = dyn_cast_or_null<CallExpr>(
429
6
                                     StmtMap->getParentIgnoreParenImpCasts(E)))
430
6
      if (FunctionDecl *
431
6
            FD = dyn_cast_or_null<FunctionDecl>(callE->getCalleeDecl())) {
432
6
        unsigned i = 0;
433
7
        for (unsigned e = callE->getNumArgs(); i != e; 
++i1
) {
434
7
          Expr *arg = callE->getArg(i);
435
7
          if (arg == E || 
arg->IgnoreParenImpCasts() == E2
)
436
6
            break;
437
7
        }
438
6
        if (i < callE->getNumArgs() && i < FD->getNumParams()) {
439
5
          ParmVarDecl *PD = FD->getParamDecl(i);
440
5
          if (PD->hasAttr<CFConsumedAttr>()) {
441
4
            isConsumed = true;
442
4
            return true;
443
4
          }
444
48
        }
445
6
      }
446
48
447
48
    return false;
448
48
  }
449
450
85
  bool isSelf(Expr *E) const {
451
85
    E = E->IgnoreParenLValueCasts();
452
85
    if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
453
16
      if (ImplicitParamDecl *IPD = dyn_cast<ImplicitParamDecl>(DRE->getDecl()))
454
4
        if (IPD->getIdentifier() == SelfII)
455
4
          return true;
456
81
457
81
    return false;
458
81
  }
459
};
460
461
} // end anonymous namespace
462
463
85
void trans::rewriteUnbridgedCasts(MigrationPass &pass) {
464
85
  BodyTransform<UnbridgedCastRewriter> trans(pass);
465
85
  trans.TraverseDecl(pass.Ctx.getTranslationUnitDecl());
466
85
}