Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/lib/Transforms/InstCombine/InstCombineCasts.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- InstCombineCasts.cpp -----------------------------------------------===//
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
// This file implements the visit functions for cast operations.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "InstCombineInternal.h"
14
#include "llvm/ADT/SetVector.h"
15
#include "llvm/Analysis/ConstantFolding.h"
16
#include "llvm/Analysis/TargetLibraryInfo.h"
17
#include "llvm/IR/DataLayout.h"
18
#include "llvm/IR/DIBuilder.h"
19
#include "llvm/IR/PatternMatch.h"
20
#include "llvm/Support/KnownBits.h"
21
using namespace llvm;
22
using namespace PatternMatch;
23
24
#define DEBUG_TYPE "instcombine"
25
26
/// Analyze 'Val', seeing if it is a simple linear expression.
27
/// If so, decompose it, returning some value X, such that Val is
28
/// X*Scale+Offset.
29
///
30
static Value *decomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
31
1.47k
                                        uint64_t &Offset) {
32
1.47k
  if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
33
1.16k
    Offset = CI->getZExtValue();
34
1.16k
    Scale  = 0;
35
1.16k
    return ConstantInt::get(Val->getType(), 0);
36
1.16k
  }
37
311
38
311
  if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
39
285
    // Cannot look past anything that might overflow.
40
285
    OverflowingBinaryOperator *OBI = dyn_cast<OverflowingBinaryOperator>(Val);
41
285
    if (OBI && 
!OBI->hasNoUnsignedWrap()254
&&
!OBI->hasNoSignedWrap()106
) {
42
51
      Scale = 1;
43
51
      Offset = 0;
44
51
      return Val;
45
51
    }
46
234
47
234
    if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
48
234
      if (I->getOpcode() == Instruction::Shl) {
49
41
        // This is a value scaled by '1 << the shift amt'.
50
41
        Scale = UINT64_C(1) << RHS->getZExtValue();
51
41
        Offset = 0;
52
41
        return I->getOperand(0);
53
41
      }
54
193
55
193
      if (I->getOpcode() == Instruction::Mul) {
56
74
        // This value is scaled by 'RHS'.
57
74
        Scale = RHS->getZExtValue();
58
74
        Offset = 0;
59
74
        return I->getOperand(0);
60
74
      }
61
119
62
119
      if (I->getOpcode() == Instruction::Add) {
63
88
        // We have X+C.  Check to see if we really have (X*C2)+C1,
64
88
        // where C1 is divisible by C2.
65
88
        unsigned SubScale;
66
88
        Value *SubVal =
67
88
          decomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
68
88
        Offset += RHS->getZExtValue();
69
88
        Scale = SubScale;
70
88
        return SubVal;
71
88
      }
72
57
    }
73
234
  }
74
57
75
57
  // Otherwise, we can't look past this.
76
57
  Scale = 1;
77
57
  Offset = 0;
78
57
  return Val;
79
57
}
80
81
/// If we find a cast of an allocation instruction, try to eliminate the cast by
82
/// moving the type information into the alloc.
83
Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
84
1.04M
                                                   AllocaInst &AI) {
85
1.04M
  PointerType *PTy = cast<PointerType>(CI.getType());
86
1.04M
87
1.04M
  BuilderTy AllocaBuilder(Builder);
88
1.04M
  AllocaBuilder.SetInsertPoint(&AI);
89
1.04M
90
1.04M
  // Get the type really allocated and the type casted to.
91
1.04M
  Type *AllocElTy = AI.getAllocatedType();
92
1.04M
  Type *CastElTy = PTy->getElementType();
93
1.04M
  if (!AllocElTy->isSized() || !CastElTy->isSized()) 
return nullptr3.10k
;
94
1.03M
95
1.03M
  unsigned AllocElTyAlign = DL.getABITypeAlignment(AllocElTy);
96
1.03M
  unsigned CastElTyAlign = DL.getABITypeAlignment(CastElTy);
97
1.03M
  if (CastElTyAlign < AllocElTyAlign) 
return nullptr821k
;
98
216k
99
216k
  // If the allocation has multiple uses, only promote it if we are strictly
100
216k
  // increasing the alignment of the resultant allocation.  If we keep it the
101
216k
  // same, we open the door to infinite loops of various kinds.
102
216k
  if (!AI.hasOneUse() && 
CastElTyAlign == AllocElTyAlign216k
)
return nullptr183k
;
103
33.0k
104
33.0k
  uint64_t AllocElTySize = DL.getTypeAllocSize(AllocElTy);
105
33.0k
  uint64_t CastElTySize = DL.getTypeAllocSize(CastElTy);
106
33.0k
  if (CastElTySize == 0 || 
AllocElTySize == 033.0k
)
return nullptr7
;
107
33.0k
108
33.0k
  // If the allocation has multiple uses, only promote it if we're not
109
33.0k
  // shrinking the amount of memory being allocated.
110
33.0k
  uint64_t AllocElTyStoreSize = DL.getTypeStoreSize(AllocElTy);
111
33.0k
  uint64_t CastElTyStoreSize = DL.getTypeStoreSize(CastElTy);
112
33.0k
  if (!AI.hasOneUse() && 
CastElTyStoreSize < AllocElTyStoreSize32.9k
)
return nullptr31.6k
;
113
1.39k
114
1.39k
  // See if we can satisfy the modulus by pulling a scale out of the array
115
1.39k
  // size argument.
116
1.39k
  unsigned ArraySizeScale;
117
1.39k
  uint64_t ArrayOffset;
118
1.39k
  Value *NumElements = // See if the array size is a decomposable linear expr.
119
1.39k
    decomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
120
1.39k
121
1.39k
  // If we can now satisfy the modulus, by using a non-1 scale, we really can
122
1.39k
  // do the xform.
123
1.39k
  if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
124
1.39k
      
(AllocElTySize*ArrayOffset ) % CastElTySize != 01.24k
)
return nullptr315
;
125
1.07k
126
1.07k
  unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
127
1.07k
  Value *Amt = nullptr;
128
1.07k
  if (Scale == 1) {
129
41
    Amt = NumElements;
130
1.03k
  } else {
131
1.03k
    Amt = ConstantInt::get(AI.getArraySize()->getType(), Scale);
132
1.03k
    // Insert before the alloca, not before the cast.
133
1.03k
    Amt = AllocaBuilder.CreateMul(Amt, NumElements);
134
1.03k
  }
135
1.07k
136
1.07k
  if (uint64_t Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
137
1.03k
    Value *Off = ConstantInt::get(AI.getArraySize()->getType(),
138
1.03k
                                  Offset, true);
139
1.03k
    Amt = AllocaBuilder.CreateAdd(Amt, Off);
140
1.03k
  }
141
1.07k
142
1.07k
  AllocaInst *New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
143
1.07k
  New->setAlignment(AI.getAlignment());
144
1.07k
  New->takeName(&AI);
145
1.07k
  New->setUsedWithInAlloca(AI.isUsedWithInAlloca());
146
1.07k
147
1.07k
  // If the allocation has multiple real uses, insert a cast and change all
148
1.07k
  // things that used it to use the new cast.  This will also hack on CI, but it
149
1.07k
  // will die soon.
150
1.07k
  if (!AI.hasOneUse()) {
151
954
    // New is the allocation instruction, pointer typed. AI is the original
152
954
    // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
153
954
    Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
154
954
    replaceInstUsesWith(AI, NewCast);
155
954
  }
156
1.07k
  return replaceInstUsesWith(CI, New);
157
1.07k
}
158
159
/// Given an expression that CanEvaluateTruncated or CanEvaluateSExtd returns
160
/// true for, actually insert the code to evaluate the expression.
161
Value *InstCombiner::EvaluateInDifferentType(Value *V, Type *Ty,
162
35.0k
                                             bool isSigned) {
163
35.0k
  if (Constant *C = dyn_cast<Constant>(V)) {
164
7.31k
    C = ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
165
7.31k
    // If we got a constantexpr back, try to simplify it with DL info.
166
7.31k
    if (Constant *FoldedC = ConstantFoldConstant(C, DL, &TLI))
167
1
      C = FoldedC;
168
7.31k
    return C;
169
7.31k
  }
170
27.7k
171
27.7k
  // Otherwise, it must be an instruction.
172
27.7k
  Instruction *I = cast<Instruction>(V);
173
27.7k
  Instruction *Res = nullptr;
174
27.7k
  unsigned Opc = I->getOpcode();
175
27.7k
  switch (Opc) {
176
27.7k
  case Instruction::Add:
177
7.35k
  case Instruction::Sub:
178
7.35k
  case Instruction::Mul:
179
7.35k
  case Instruction::And:
180
7.35k
  case Instruction::Or:
181
7.35k
  case Instruction::Xor:
182
7.35k
  case Instruction::AShr:
183
7.35k
  case Instruction::LShr:
184
7.35k
  case Instruction::Shl:
185
7.35k
  case Instruction::UDiv:
186
7.35k
  case Instruction::URem: {
187
7.35k
    Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
188
7.35k
    Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
189
7.35k
    Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
190
7.35k
    break;
191
7.35k
  }
192
17.8k
  case Instruction::Trunc:
193
17.8k
  case Instruction::ZExt:
194
17.8k
  case Instruction::SExt:
195
17.8k
    // If the source type of the cast is the type we're trying for then we can
196
17.8k
    // just return the source.  There's no need to insert it because it is not
197
17.8k
    // new.
198
17.8k
    if (I->getOperand(0)->getType() == Ty)
199
14.4k
      return I->getOperand(0);
200
3.37k
201
3.37k
    // Otherwise, must be the same type of cast, so just reinsert a new one.
202
3.37k
    // This also handles the case of zext(trunc(x)) -> zext(x).
203
3.37k
    Res = CastInst::CreateIntegerCast(I->getOperand(0), Ty,
204
3.37k
                                      Opc == Instruction::SExt);
205
3.37k
    break;
206
3.37k
  case Instruction::Select: {
207
338
    Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
208
338
    Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
209
338
    Res = SelectInst::Create(I->getOperand(0), True, False);
210
338
    break;
211
3.37k
  }
212
3.37k
  case Instruction::PHI: {
213
2.23k
    PHINode *OPN = cast<PHINode>(I);
214
2.23k
    PHINode *NPN = PHINode::Create(Ty, OPN->getNumIncomingValues());
215
8.85k
    for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; 
++i6.61k
) {
216
6.61k
      Value *V =
217
6.61k
          EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
218
6.61k
      NPN->addIncoming(V, OPN->getIncomingBlock(i));
219
6.61k
    }
220
2.23k
    Res = NPN;
221
2.23k
    break;
222
3.37k
  }
223
3.37k
  default:
224
0
    // TODO: Can handle more cases here.
225
0
    llvm_unreachable("Unreachable!");
226
13.2k
  }
227
13.2k
228
13.2k
  Res->takeName(I);
229
13.2k
  return InsertNewInstWith(Res, *I);
230
13.2k
}
231
232
Instruction::CastOps InstCombiner::isEliminableCastPair(const CastInst *CI1,
233
256k
                                                        const CastInst *CI2) {
234
256k
  Type *SrcTy = CI1->getSrcTy();
235
256k
  Type *MidTy = CI1->getDestTy();
236
256k
  Type *DstTy = CI2->getDestTy();
237
256k
238
256k
  Instruction::CastOps firstOp = CI1->getOpcode();
239
256k
  Instruction::CastOps secondOp = CI2->getOpcode();
240
256k
  Type *SrcIntPtrTy =
241
256k
      SrcTy->isPtrOrPtrVectorTy() ? 
DL.getIntPtrType(SrcTy)81.2k
:
nullptr175k
;
242
256k
  Type *MidIntPtrTy =
243
256k
      MidTy->isPtrOrPtrVectorTy() ? 
DL.getIntPtrType(MidTy)69.9k
:
nullptr186k
;
244
256k
  Type *DstIntPtrTy =
245
256k
      DstTy->isPtrOrPtrVectorTy() ? 
DL.getIntPtrType(DstTy)71.3k
:
nullptr185k
;
246
256k
  unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
247
256k
                                                DstTy, SrcIntPtrTy, MidIntPtrTy,
248
256k
                                                DstIntPtrTy);
249
256k
250
256k
  // We don't want to form an inttoptr or ptrtoint that converts to an integer
251
256k
  // type that differs from the pointer size.
252
256k
  if ((Res == Instruction::IntToPtr && 
SrcTy != DstIntPtrTy3.01k
) ||
253
256k
      
(255k
Res == Instruction::PtrToInt255k
&&
DstTy != SrcIntPtrTy11.6k
))
254
8.98k
    Res = 0;
255
256k
256
256k
  return Instruction::CastOps(Res);
257
256k
}
258
259
/// Implement the transforms common to all CastInst visitors.
260
15.3M
Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
261
15.3M
  Value *Src = CI.getOperand(0);
262
15.3M
263
15.3M
  // Try to eliminate a cast of a cast.
264
15.3M
  if (auto *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
265
256k
    if (Instruction::CastOps NewOpc = isEliminableCastPair(CSrc, &CI)) {
266
87.2k
      // The first cast (CSrc) is eliminable so we need to fix up or replace
267
87.2k
      // the second cast (CI). CSrc will then have a good chance of being dead.
268
87.2k
      auto *Ty = CI.getType();
269
87.2k
      auto *Res = CastInst::Create(NewOpc, CSrc->getOperand(0), Ty);
270
87.2k
      // Point debug users of the dying cast to the new one.
271
87.2k
      if (CSrc->hasOneUse())
272
60.3k
        replaceAllDbgUsesWith(*CSrc, *Res, CI, DT);
273
87.2k
      return Res;
274
87.2k
    }
275
15.2M
  }
276
15.2M
277
15.2M
  if (auto *Sel = dyn_cast<SelectInst>(Src)) {
278
218k
    // We are casting a select. Try to fold the cast into the select, but only
279
218k
    // if the select does not have a compare instruction with matching operand
280
218k
    // types. Creating a select with operands that are different sizes than its
281
218k
    // condition may inhibit other folds and lead to worse codegen.
282
218k
    auto *Cmp = dyn_cast<CmpInst>(Sel->getCondition());
283
218k
    if (!Cmp || 
Cmp->getOperand(0)->getType() != Sel->getType()197k
)
284
99.3k
      if (Instruction *NV = FoldOpIntoSelect(CI, Sel)) {
285
550
        replaceAllDbgUsesWith(*Sel, *NV, CI, DT);
286
550
        return NV;
287
550
      }
288
15.2M
  }
289
15.2M
290
15.2M
  // If we are casting a PHI, then fold the cast into the PHI.
291
15.2M
  if (auto *PN = dyn_cast<PHINode>(Src)) {
292
1.15M
    // Don't do this if it would create a PHI node with an illegal type from a
293
1.15M
    // legal type.
294
1.15M
    if (!Src->getType()->isIntegerTy() || 
!CI.getType()->isIntegerTy()722k
||
295
1.15M
        
shouldChangeType(CI.getType(), Src->getType())564k
)
296
1.15M
      if (Instruction *NV = foldOpIntoPhi(CI, PN))
297
3.04k
        return NV;
298
15.2M
  }
299
15.2M
300
15.2M
  return nullptr;
301
15.2M
}
302
303
/// Constants and extensions/truncates from the destination type are always
304
/// free to be evaluated in that type. This is a helper for canEvaluate*.
305
6.02M
static bool canAlwaysEvaluateInType(Value *V, Type *Ty) {
306
6.02M
  if (isa<Constant>(V))
307
105k
    return true;
308
5.92M
  Value *X;
309
5.92M
  if ((match(V, m_ZExtOrSExt(m_Value(X))) || 
match(V, m_Trunc(m_Value(X)))5.89M
) &&
310
5.92M
      
X->getType() == Ty49.3k
)
311
32.4k
    return true;
312
5.89M
313
5.89M
  return false;
314
5.89M
}
315
316
/// Filter out values that we can not evaluate in the destination type for free.
317
/// This is a helper for canEvaluate*.
318
5.89M
static bool canNotEvaluateInType(Value *V, Type *Ty) {
319
5.89M
  assert(!isa<Constant>(V) && "Constant should already be handled.");
320
5.89M
  if (!isa<Instruction>(V))
321
770k
    return true;
322
5.12M
  // We don't extend or shrink something that has multiple uses --  doing so
323
5.12M
  // would require duplicating the instruction which isn't profitable.
324
5.12M
  if (!V->hasOneUse())
325
2.49M
    return true;
326
2.62M
327
2.62M
  return false;
328
2.62M
}
329
330
/// Return true if we can evaluate the specified expression tree as type Ty
331
/// instead of its larger type, and arrive with the same value.
332
/// This is used by code that tries to eliminate truncates.
333
///
334
/// Ty will always be a type smaller than V.  We should return true if trunc(V)
335
/// can be computed by computing V in the smaller type.  If V is an instruction,
336
/// then trunc(inst(x,y)) can be computed as inst(trunc(x),trunc(y)), which only
337
/// makes sense if x and y can be efficiently truncated.
338
///
339
/// This function works on both vectors and scalars.
340
///
341
static bool canEvaluateTruncated(Value *V, Type *Ty, InstCombiner &IC,
342
1.49M
                                 Instruction *CxtI) {
343
1.49M
  if (canAlwaysEvaluateInType(V, Ty))
344
19.9k
    return true;
345
1.47M
  if (canNotEvaluateInType(V, Ty))
346
877k
    return false;
347
602k
348
602k
  auto *I = cast<Instruction>(V);
349
602k
  Type *OrigTy = V->getType();
350
602k
  switch (I->getOpcode()) {
351
602k
  case Instruction::Add:
352
100k
  case Instruction::Sub:
353
100k
  case Instruction::Mul:
354
100k
  case Instruction::And:
355
100k
  case Instruction::Or:
356
100k
  case Instruction::Xor:
357
100k
    // These operators can all arbitrarily be extended or truncated.
358
100k
    return canEvaluateTruncated(I->getOperand(0), Ty, IC, CxtI) &&
359
100k
           
canEvaluateTruncated(I->getOperand(1), Ty, IC, CxtI)4.74k
;
360
100k
361
100k
  case Instruction::UDiv:
362
3.21k
  case Instruction::URem: {
363
3.21k
    // UDiv and URem can be truncated if all the truncated bits are zero.
364
3.21k
    uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
365
3.21k
    uint32_t BitWidth = Ty->getScalarSizeInBits();
366
3.21k
    assert(BitWidth < OrigBitWidth && "Unexpected bitwidths!");
367
3.21k
    APInt Mask = APInt::getBitsSetFrom(OrigBitWidth, BitWidth);
368
3.21k
    if (IC.MaskedValueIsZero(I->getOperand(0), Mask, 0, CxtI) &&
369
3.21k
        
IC.MaskedValueIsZero(I->getOperand(1), Mask, 0, CxtI)284
) {
370
69
      return canEvaluateTruncated(I->getOperand(0), Ty, IC, CxtI) &&
371
69
             
canEvaluateTruncated(I->getOperand(1), Ty, IC, CxtI)6
;
372
69
    }
373
3.14k
    break;
374
3.14k
  }
375
12.0k
  case Instruction::Shl: {
376
12.0k
    // If we are truncating the result of this SHL, and if it's a shift of a
377
12.0k
    // constant amount, we can always perform a SHL in a smaller type.
378
12.0k
    const APInt *Amt;
379
12.0k
    if (match(I->getOperand(1), m_APInt(Amt))) {
380
5.98k
      uint32_t BitWidth = Ty->getScalarSizeInBits();
381
5.98k
      if (Amt->getLimitedValue(BitWidth) < BitWidth)
382
5.87k
        return canEvaluateTruncated(I->getOperand(0), Ty, IC, CxtI);
383
6.18k
    }
384
6.18k
    break;
385
6.18k
  }
386
254k
  case Instruction::LShr: {
387
254k
    // If this is a truncate of a logical shr, we can truncate it to a smaller
388
254k
    // lshr iff we know that the bits we would otherwise be shifting in are
389
254k
    // already zeros.
390
254k
    const APInt *Amt;
391
254k
    if (match(I->getOperand(1), m_APInt(Amt))) {
392
249k
      uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
393
249k
      uint32_t BitWidth = Ty->getScalarSizeInBits();
394
249k
      if (Amt->getLimitedValue(BitWidth) < BitWidth &&
395
249k
          IC.MaskedValueIsZero(I->getOperand(0),
396
30.1k
            APInt::getBitsSetFrom(OrigBitWidth, BitWidth), 0, CxtI)) {
397
710
        return canEvaluateTruncated(I->getOperand(0), Ty, IC, CxtI);
398
710
      }
399
253k
    }
400
253k
    break;
401
253k
  }
402
253k
  case Instruction::AShr: {
403
4.92k
    // If this is a truncate of an arithmetic shr, we can truncate it to a
404
4.92k
    // smaller ashr iff we know that all the bits from the sign bit of the
405
4.92k
    // original type and the sign bit of the truncate type are similar.
406
4.92k
    // TODO: It is enough to check that the bits we would be shifting in are
407
4.92k
    //       similar to sign bit of the truncate type.
408
4.92k
    const APInt *Amt;
409
4.92k
    if (match(I->getOperand(1), m_APInt(Amt))) {
410
3.81k
      uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
411
3.81k
      uint32_t BitWidth = Ty->getScalarSizeInBits();
412
3.81k
      if (Amt->getLimitedValue(BitWidth) < BitWidth &&
413
3.81k
          OrigBitWidth - BitWidth <
414
1.95k
              IC.ComputeNumSignBits(I->getOperand(0), 0, CxtI))
415
44
        return canEvaluateTruncated(I->getOperand(0), Ty, IC, CxtI);
416
4.87k
    }
417
4.87k
    break;
418
4.87k
  }
419
4.87k
  case Instruction::Trunc:
420
210
    // trunc(trunc(x)) -> trunc(x)
421
210
    return true;
422
4.87k
  case Instruction::ZExt:
423
1.17k
  case Instruction::SExt:
424
1.17k
    // trunc(ext(x)) -> ext(x) if the source type is smaller than the new dest
425
1.17k
    // trunc(ext(x)) -> trunc(x) if the source type is larger than the new dest
426
1.17k
    return true;
427
31.5k
  case Instruction::Select: {
428
31.5k
    SelectInst *SI = cast<SelectInst>(I);
429
31.5k
    return canEvaluateTruncated(SI->getTrueValue(), Ty, IC, CxtI) &&
430
31.5k
           
canEvaluateTruncated(SI->getFalseValue(), Ty, IC, CxtI)4.55k
;
431
1.17k
  }
432
12.3k
  case Instruction::PHI: {
433
12.3k
    // We can change a phi if we can change all operands.  Note that we never
434
12.3k
    // get into trouble with cyclic PHIs here because we only consider
435
12.3k
    // instructions with a single use.
436
12.3k
    PHINode *PN = cast<PHINode>(I);
437
12.3k
    for (Value *IncValue : PN->incoming_values())
438
19.9k
      if (!canEvaluateTruncated(IncValue, Ty, IC, CxtI))
439
10.5k
        return false;
440
12.3k
    
return true1.86k
;
441
12.3k
  }
442
182k
  default:
443
182k
    // TODO: Can handle more cases here.
444
182k
    break;
445
450k
  }
446
450k
447
450k
  return false;
448
450k
}
449
450
/// Given a vector that is bitcast to an integer, optionally logically
451
/// right-shifted, and truncated, convert it to an extractelement.
452
/// Example (big endian):
453
///   trunc (lshr (bitcast <4 x i32> %X to i128), 32) to i32
454
///   --->
455
///   extractelement <4 x i32> %X, 1
456
1.26M
static Instruction *foldVecTruncToExtElt(TruncInst &Trunc, InstCombiner &IC) {
457
1.26M
  Value *TruncOp = Trunc.getOperand(0);
458
1.26M
  Type *DestType = Trunc.getType();
459
1.26M
  if (!TruncOp->hasOneUse() || 
!isa<IntegerType>(DestType)477k
)
460
797k
    return nullptr;
461
472k
462
472k
  Value *VecInput = nullptr;
463
472k
  ConstantInt *ShiftVal = nullptr;
464
472k
  if (!match(TruncOp, m_CombineOr(m_BitCast(m_Value(VecInput)),
465
472k
                                  m_LShr(m_BitCast(m_Value(VecInput)),
466
472k
                                         m_ConstantInt(ShiftVal)))) ||
467
472k
      
!isa<VectorType>(VecInput->getType())6.16k
)
468
472k
    return nullptr;
469
38
470
38
  VectorType *VecType = cast<VectorType>(VecInput->getType());
471
38
  unsigned VecWidth = VecType->getPrimitiveSizeInBits();
472
38
  unsigned DestWidth = DestType->getPrimitiveSizeInBits();
473
38
  unsigned ShiftAmount = ShiftVal ? 
ShiftVal->getZExtValue()6
:
032
;
474
38
475
38
  if ((VecWidth % DestWidth != 0) || 
(ShiftAmount % DestWidth != 0)37
)
476
1
    return nullptr;
477
37
478
37
  // If the element type of the vector doesn't match the result type,
479
37
  // bitcast it to a vector type that we can extract from.
480
37
  unsigned NumVecElts = VecWidth / DestWidth;
481
37
  if (VecType->getElementType() != DestType) {
482
33
    VecType = VectorType::get(DestType, NumVecElts);
483
33
    VecInput = IC.Builder.CreateBitCast(VecInput, VecType, "bc");
484
33
  }
485
37
486
37
  unsigned Elt = ShiftAmount / DestWidth;
487
37
  if (IC.getDataLayout().isBigEndian())
488
4
    Elt = NumVecElts - 1 - Elt;
489
37
490
37
  return ExtractElementInst::Create(VecInput, IC.Builder.getInt32(Elt));
491
37
}
492
493
/// Rotate left/right may occur in a wider type than necessary because of type
494
/// promotion rules. Try to narrow the inputs and convert to funnel shift.
495
313k
Instruction *InstCombiner::narrowRotate(TruncInst &Trunc) {
496
313k
  assert((isa<VectorType>(Trunc.getSrcTy()) ||
497
313k
          shouldChangeType(Trunc.getSrcTy(), Trunc.getType())) &&
498
313k
         "Don't narrow to an illegal scalar type");
499
313k
500
313k
  // Bail out on strange types. It is possible to handle some of these patterns
501
313k
  // even with non-power-of-2 sizes, but it is not a likely scenario.
502
313k
  Type *DestTy = Trunc.getType();
503
313k
  unsigned NarrowWidth = DestTy->getScalarSizeInBits();
504
313k
  if (!isPowerOf2_32(NarrowWidth))
505
95
    return nullptr;
506
313k
507
313k
  // First, find an or'd pair of opposite shifts with the same shifted operand:
508
313k
  // trunc (or (lshr ShVal, ShAmt0), (shl ShVal, ShAmt1))
509
313k
  Value *Or0, *Or1;
510
313k
  if (!match(Trunc.getOperand(0), m_OneUse(m_Or(m_Value(Or0), m_Value(Or1)))))
511
309k
    return nullptr;
512
3.88k
513
3.88k
  Value *ShVal, *ShAmt0, *ShAmt1;
514
3.88k
  if (!match(Or0, m_OneUse(m_LogicalShift(m_Value(ShVal), m_Value(ShAmt0)))) ||
515
3.88k
      
!match(Or1, m_OneUse(m_LogicalShift(m_Specific(ShVal), m_Value(ShAmt1))))1.00k
)
516
3.79k
    return nullptr;
517
91
518
91
  auto ShiftOpcode0 = cast<BinaryOperator>(Or0)->getOpcode();
519
91
  auto ShiftOpcode1 = cast<BinaryOperator>(Or1)->getOpcode();
520
91
  if (ShiftOpcode0 == ShiftOpcode1)
521
0
    return nullptr;
522
91
523
91
  // Match the shift amount operands for a rotate pattern. This always matches
524
91
  // a subtraction on the R operand.
525
176
  
auto matchShiftAmount = [](Value *L, Value *R, unsigned Width) -> Value * 91
{
526
176
    // The shift amounts may add up to the narrow bit width:
527
176
    // (shl ShVal, L) | (lshr ShVal, Width - L)
528
176
    if (match(R, m_OneUse(m_Sub(m_SpecificInt(Width), m_Specific(L)))))
529
5
      return L;
530
171
531
171
    // The shift amount may be masked with negation:
532
171
    // (shl ShVal, (X & (Width - 1))) | (lshr ShVal, ((-X) & (Width - 1)))
533
171
    Value *X;
534
171
    unsigned Mask = Width - 1;
535
171
    if (match(L, m_And(m_Value(X), m_SpecificInt(Mask))) &&
536
171
        
match(R, m_And(m_Neg(m_Specific(X)), m_SpecificInt(Mask)))6
)
537
4
      return X;
538
167
539
167
    // Same as above, but the shift amount may be extended after masking:
540
167
    if (match(L, m_ZExt(m_And(m_Value(X), m_SpecificInt(Mask)))) &&
541
167
        
match(R, m_ZExt(m_And(m_Neg(m_Specific(X)), m_SpecificInt(Mask))))63
)
542
4
      return X;
543
163
544
163
    return nullptr;
545
163
  };
546
91
547
91
  Value *ShAmt = matchShiftAmount(ShAmt0, ShAmt1, NarrowWidth);
548
91
  bool SubIsOnLHS = false;
549
91
  if (!ShAmt) {
550
85
    ShAmt = matchShiftAmount(ShAmt1, ShAmt0, NarrowWidth);
551
85
    SubIsOnLHS = true;
552
85
  }
553
91
  if (!ShAmt)
554
78
    return nullptr;
555
13
556
13
  // The shifted value must have high zeros in the wide type. Typically, this
557
13
  // will be a zext, but it could also be the result of an 'and' or 'shift'.
558
13
  unsigned WideWidth = Trunc.getSrcTy()->getScalarSizeInBits();
559
13
  APInt HiBitMask = APInt::getHighBitsSet(WideWidth, WideWidth - NarrowWidth);
560
13
  if (!MaskedValueIsZero(ShVal, HiBitMask, 0, &Trunc))
561
0
    return nullptr;
562
13
563
13
  // We have an unnecessarily wide rotate!
564
13
  // trunc (or (lshr ShVal, ShAmt), (shl ShVal, BitWidth - ShAmt))
565
13
  // Narrow the inputs and convert to funnel shift intrinsic:
566
13
  // llvm.fshl.i8(trunc(ShVal), trunc(ShVal), trunc(ShAmt))
567
13
  Value *NarrowShAmt = Builder.CreateTrunc(ShAmt, DestTy);
568
13
  Value *X = Builder.CreateTrunc(ShVal, DestTy);
569
13
  bool IsFshl = (!SubIsOnLHS && 
ShiftOpcode0 == BinaryOperator::Shl6
) ||
570
13
                
(10
SubIsOnLHS10
&&
ShiftOpcode1 == BinaryOperator::Shl7
);
571
13
  Intrinsic::ID IID = IsFshl ? 
Intrinsic::fshl7
:
Intrinsic::fshr6
;
572
13
  Function *F = Intrinsic::getDeclaration(Trunc.getModule(), IID, DestTy);
573
13
  return IntrinsicInst::Create(F, { X, X, NarrowShAmt });
574
13
}
575
576
/// Try to narrow the width of math or bitwise logic instructions by pulling a
577
/// truncate ahead of binary operators.
578
/// TODO: Transforms for truncated shifts should be moved into here.
579
1.29M
Instruction *InstCombiner::narrowBinOp(TruncInst &Trunc) {
580
1.29M
  Type *SrcTy = Trunc.getSrcTy();
581
1.29M
  Type *DestTy = Trunc.getType();
582
1.29M
  if (!isa<VectorType>(SrcTy) && 
!shouldChangeType(SrcTy, DestTy)1.20M
)
583
603
    return nullptr;
584
1.28M
585
1.28M
  BinaryOperator *BinOp;
586
1.28M
  if (!match(Trunc.getOperand(0), m_OneUse(m_BinOp(BinOp))))
587
956k
    return nullptr;
588
332k
589
332k
  Value *BinOp0 = BinOp->getOperand(0);
590
332k
  Value *BinOp1 = BinOp->getOperand(1);
591
332k
  switch (BinOp->getOpcode()) {
592
332k
  case Instruction::And:
593
50.5k
  case Instruction::Or:
594
50.5k
  case Instruction::Xor:
595
50.5k
  case Instruction::Add:
596
50.5k
  case Instruction::Sub:
597
50.5k
  case Instruction::Mul: {
598
50.5k
    Constant *C;
599
50.5k
    if (match(BinOp0, m_Constant(C))) {
600
290
      // trunc (binop C, X) --> binop (trunc C', X)
601
290
      Constant *NarrowC = ConstantExpr::getTrunc(C, DestTy);
602
290
      Value *TruncX = Builder.CreateTrunc(BinOp1, DestTy);
603
290
      return BinaryOperator::Create(BinOp->getOpcode(), NarrowC, TruncX);
604
290
    }
605
50.2k
    if (match(BinOp1, m_Constant(C))) {
606
17.5k
      // trunc (binop X, C) --> binop (trunc X, C')
607
17.5k
      Constant *NarrowC = ConstantExpr::getTrunc(C, DestTy);
608
17.5k
      Value *TruncX = Builder.CreateTrunc(BinOp0, DestTy);
609
17.5k
      return BinaryOperator::Create(BinOp->getOpcode(), TruncX, NarrowC);
610
17.5k
    }
611
32.7k
    Value *X;
612
32.7k
    if (match(BinOp0, m_ZExtOrSExt(m_Value(X))) && 
X->getType() == DestTy320
) {
613
223
      // trunc (binop (ext X), Y) --> binop X, (trunc Y)
614
223
      Value *NarrowOp1 = Builder.CreateTrunc(BinOp1, DestTy);
615
223
      return BinaryOperator::Create(BinOp->getOpcode(), X, NarrowOp1);
616
223
    }
617
32.5k
    if (match(BinOp1, m_ZExtOrSExt(m_Value(X))) && 
X->getType() == DestTy1.93k
) {
618
822
      // trunc (binop Y, (ext X)) --> binop (trunc Y), X
619
822
      Value *NarrowOp0 = Builder.CreateTrunc(BinOp0, DestTy);
620
822
      return BinaryOperator::Create(BinOp->getOpcode(), NarrowOp0, X);
621
822
    }
622
31.7k
    break;
623
31.7k
  }
624
31.7k
625
282k
  default: break;
626
313k
  }
627
313k
628
313k
  if (Instruction *NarrowOr = narrowRotate(Trunc))
629
13
    return NarrowOr;
630
313k
631
313k
  return nullptr;
632
313k
}
633
634
/// Try to narrow the width of a splat shuffle. This could be generalized to any
635
/// shuffle with a constant operand, but we limit the transform to avoid
636
/// creating a shuffle type that targets may not be able to lower effectively.
637
static Instruction *shrinkSplatShuffle(TruncInst &Trunc,
638
1.27M
                                       InstCombiner::BuilderTy &Builder) {
639
1.27M
  auto *Shuf = dyn_cast<ShuffleVectorInst>(Trunc.getOperand(0));
640
1.27M
  if (Shuf && 
Shuf->hasOneUse()477
&&
isa<UndefValue>(Shuf->getOperand(1))378
&&
641
1.27M
      
Shuf->getMask()->getSplatValue()8
&&
642
1.27M
      
Shuf->getType() == Shuf->getOperand(0)->getType()7
) {
643
5
    // trunc (shuf X, Undef, SplatMask) --> shuf (trunc X), Undef, SplatMask
644
5
    Constant *NarrowUndef = UndefValue::get(Trunc.getType());
645
5
    Value *NarrowOp = Builder.CreateTrunc(Shuf->getOperand(0), Trunc.getType());
646
5
    return new ShuffleVectorInst(NarrowOp, NarrowUndef, Shuf->getMask());
647
5
  }
648
1.27M
649
1.27M
  return nullptr;
650
1.27M
}
651
652
/// Try to narrow the width of an insert element. This could be generalized for
653
/// any vector constant, but we limit the transform to insertion into undef to
654
/// avoid potential backend problems from unsupported insertion widths. This
655
/// could also be extended to handle the case of inserting a scalar constant
656
/// into a vector variable.
657
static Instruction *shrinkInsertElt(CastInst &Trunc,
658
1.32M
                                    InstCombiner::BuilderTy &Builder) {
659
1.32M
  Instruction::CastOps Opcode = Trunc.getOpcode();
660
1.32M
  assert((Opcode == Instruction::Trunc || Opcode == Instruction::FPTrunc) &&
661
1.32M
         "Unexpected instruction for shrinking");
662
1.32M
663
1.32M
  auto *InsElt = dyn_cast<InsertElementInst>(Trunc.getOperand(0));
664
1.32M
  if (!InsElt || 
!InsElt->hasOneUse()32
)
665
1.32M
    return nullptr;
666
32
667
32
  Type *DestTy = Trunc.getType();
668
32
  Type *DestScalarTy = DestTy->getScalarType();
669
32
  Value *VecOp = InsElt->getOperand(0);
670
32
  Value *ScalarOp = InsElt->getOperand(1);
671
32
  Value *Index = InsElt->getOperand(2);
672
32
673
32
  if (isa<UndefValue>(VecOp)) {
674
25
    // trunc   (inselt undef, X, Index) --> inselt undef,   (trunc X), Index
675
25
    // fptrunc (inselt undef, X, Index) --> inselt undef, (fptrunc X), Index
676
25
    UndefValue *NarrowUndef = UndefValue::get(DestTy);
677
25
    Value *NarrowOp = Builder.CreateCast(Opcode, ScalarOp, DestScalarTy);
678
25
    return InsertElementInst::Create(NarrowUndef, NarrowOp, Index);
679
25
  }
680
7
681
7
  return nullptr;
682
7
}
683
684
1.34M
Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
685
1.34M
  if (Instruction *Result = commonCastTransforms(CI))
686
9.79k
    return Result;
687
1.33M
688
1.33M
  Value *Src = CI.getOperand(0);
689
1.33M
  Type *DestTy = CI.getType(), *SrcTy = Src->getType();
690
1.33M
691
1.33M
  // Attempt to truncate the entire input expression tree to the destination
692
1.33M
  // type.   Only do this if the dest type is a simple type, don't convert the
693
1.33M
  // expression tree to something weird like i93 unless the source is also
694
1.33M
  // strange.
695
1.33M
  if ((DestTy->isVectorTy() || 
shouldChangeType(SrcTy, DestTy)1.25M
) &&
696
1.33M
      
canEvaluateTruncated(Src, DestTy, *this, &CI)1.33M
) {
697
4.40k
698
4.40k
    // If this cast is a truncate, evaluting in a different type always
699
4.40k
    // eliminates the cast, so it is always a win.
700
4.40k
    LLVM_DEBUG(
701
4.40k
        dbgs() << "ICE: EvaluateInDifferentType converting expression type"
702
4.40k
                  " to avoid cast: "
703
4.40k
               << CI << '\n');
704
4.40k
    Value *Res = EvaluateInDifferentType(Src, DestTy, false);
705
4.40k
    assert(Res->getType() == DestTy);
706
4.40k
    return replaceInstUsesWith(CI, Res);
707
4.40k
  }
708
1.32M
709
1.32M
  // Test if the trunc is the user of a select which is part of a
710
1.32M
  // minimum or maximum operation. If so, don't do any more simplification.
711
1.32M
  // Even simplifying demanded bits can break the canonical form of a
712
1.32M
  // min/max.
713
1.32M
  Value *LHS, *RHS;
714
1.32M
  if (SelectInst *SI = dyn_cast<SelectInst>(CI.getOperand(0)))
715
52.7k
    if (matchSelectPattern(SI, LHS, RHS).Flavor != SPF_UNKNOWN)
716
9.37k
      return nullptr;
717
1.31M
718
1.31M
  // See if we can simplify any instructions used by the input whose sole
719
1.31M
  // purpose is to compute bits we don't care about.
720
1.31M
  if (SimplifyDemandedInstructionBits(CI))
721
5.00k
    return &CI;
722
1.31M
723
1.31M
  if (DestTy->getScalarSizeInBits() == 1) {
724
23.7k
    Value *Zero = Constant::getNullValue(Src->getType());
725
23.7k
    if (DestTy->isIntegerTy()) {
726
23.7k
      // Canonicalize trunc x to i1 -> icmp ne (and x, 1), 0 (scalar only).
727
23.7k
      // TODO: We canonicalize to more instructions here because we are probably
728
23.7k
      // lacking equivalent analysis for trunc relative to icmp. There may also
729
23.7k
      // be codegen concerns. If those trunc limitations were removed, we could
730
23.7k
      // remove this transform.
731
23.7k
      Value *And = Builder.CreateAnd(Src, ConstantInt::get(SrcTy, 1));
732
23.7k
      return new ICmpInst(ICmpInst::ICMP_NE, And, Zero);
733
23.7k
    }
734
49
735
49
    // For vectors, we do not canonicalize all truncs to icmp, so optimize
736
49
    // patterns that would be covered within visitICmpInst.
737
49
    Value *X;
738
49
    const APInt *C;
739
49
    if (match(Src, m_OneUse(m_LShr(m_Value(X), m_APInt(C))))) {
740
12
      // trunc (lshr X, C) to i1 --> icmp ne (and X, C'), 0
741
12
      APInt MaskC = APInt(SrcTy->getScalarSizeInBits(), 1).shl(*C);
742
12
      Value *And = Builder.CreateAnd(X, ConstantInt::get(SrcTy, MaskC));
743
12
      return new ICmpInst(ICmpInst::ICMP_NE, And, Zero);
744
12
    }
745
37
    if (match(Src, m_OneUse(m_c_Or(m_LShr(m_Value(X), m_APInt(C)),
746
37
                                   m_Deferred(X))))) {
747
2
      // trunc (or (lshr X, C), X) to i1 --> icmp ne (and X, C'), 0
748
2
      APInt MaskC = APInt(SrcTy->getScalarSizeInBits(), 1).shl(*C) | 1;
749
2
      Value *And = Builder.CreateAnd(X, ConstantInt::get(SrcTy, MaskC));
750
2
      return new ICmpInst(ICmpInst::ICMP_NE, And, Zero);
751
2
    }
752
1.29M
  }
753
1.29M
754
1.29M
  // FIXME: Maybe combine the next two transforms to handle the no cast case
755
1.29M
  // more efficiently. Support vector types. Cleanup code by using m_OneUse.
756
1.29M
757
1.29M
  // Transform trunc(lshr (zext A), Cst) to eliminate one type conversion.
758
1.29M
  Value *A = nullptr; ConstantInt *Cst = nullptr;
759
1.29M
  if (Src->hasOneUse() &&
760
1.29M
      
match(Src, m_LShr(m_ZExt(m_Value(A)), m_ConstantInt(Cst)))497k
) {
761
123
    // We have three types to worry about here, the type of A, the source of
762
123
    // the truncate (MidSize), and the destination of the truncate. We know that
763
123
    // ASize < MidSize   and MidSize > ResultSize, but don't know the relation
764
123
    // between ASize and ResultSize.
765
123
    unsigned ASize = A->getType()->getPrimitiveSizeInBits();
766
123
767
123
    // If the shift amount is larger than the size of A, then the result is
768
123
    // known to be zero because all the input bits got shifted out.
769
123
    if (Cst->getZExtValue() >= ASize)
770
0
      return replaceInstUsesWith(CI, Constant::getNullValue(DestTy));
771
123
772
123
    // Since we're doing an lshr and a zero extend, and know that the shift
773
123
    // amount is smaller than ASize, it is always safe to do the shift in A's
774
123
    // type, then zero extend or truncate to the result.
775
123
    Value *Shift = Builder.CreateLShr(A, Cst->getZExtValue());
776
123
    Shift->takeName(Src);
777
123
    return CastInst::CreateIntegerCast(Shift, DestTy, false);
778
123
  }
779
1.29M
780
1.29M
  // FIXME: We should canonicalize to zext/trunc and remove this transform.
781
1.29M
  // Transform trunc(lshr (sext A), Cst) to ashr A, Cst to eliminate type
782
1.29M
  // conversion.
783
1.29M
  // It works because bits coming from sign extension have the same value as
784
1.29M
  // the sign bit of the original value; performing ashr instead of lshr
785
1.29M
  // generates bits of the same value as the sign bit.
786
1.29M
  if (Src->hasOneUse() &&
787
1.29M
      
match(Src, m_LShr(m_SExt(m_Value(A)), m_ConstantInt(Cst)))497k
) {
788
138
    Value *SExt = cast<Instruction>(Src)->getOperand(0);
789
138
    const unsigned SExtSize = SExt->getType()->getPrimitiveSizeInBits();
790
138
    const unsigned ASize = A->getType()->getPrimitiveSizeInBits();
791
138
    const unsigned CISize = CI.getType()->getPrimitiveSizeInBits();
792
138
    const unsigned MaxAmt = SExtSize - std::max(CISize, ASize);
793
138
    unsigned ShiftAmt = Cst->getZExtValue();
794
138
795
138
    // This optimization can be only performed when zero bits generated by
796
138
    // the original lshr aren't pulled into the value after truncation, so we
797
138
    // can only shift by values no larger than the number of extension bits.
798
138
    // FIXME: Instead of bailing when the shift is too large, use and to clear
799
138
    // the extra bits.
800
138
    if (ShiftAmt <= MaxAmt) {
801
95
      if (CISize == ASize)
802
7
        return BinaryOperator::CreateAShr(A, ConstantInt::get(CI.getType(),
803
7
                                          std::min(ShiftAmt, ASize - 1)));
804
88
      if (SExt->hasOneUse()) {
805
2
        Value *Shift = Builder.CreateAShr(A, std::min(ShiftAmt, ASize - 1));
806
2
        Shift->takeName(Src);
807
2
        return CastInst::CreateIntegerCast(Shift, CI.getType(), true);
808
2
      }
809
1.29M
    }
810
138
  }
811
1.29M
812
1.29M
  if (Instruction *I = narrowBinOp(CI))
813
18.8k
    return I;
814
1.27M
815
1.27M
  if (Instruction *I = shrinkSplatShuffle(CI, Builder))
816
5
    return I;
817
1.27M
818
1.27M
  if (Instruction *I = shrinkInsertElt(CI, Builder))
819
24
    return I;
820
1.27M
821
1.27M
  if (Src->hasOneUse() && 
isa<IntegerType>(SrcTy)478k
&&
822
1.27M
      
shouldChangeType(SrcTy, DestTy)473k
) {
823
473k
    // Transform "trunc (shl X, cst)" -> "shl (trunc X), cst" so long as the
824
473k
    // dest type is native and cst < dest size.
825
473k
    if (match(Src, m_Shl(m_Value(A), m_ConstantInt(Cst))) &&
826
473k
        
!match(A, m_Shr(m_Value(), m_Constant()))2.38k
) {
827
1.68k
      // Skip shifts of shift by constants. It undoes a combine in
828
1.68k
      // FoldShiftByConstant and is the extend in reg pattern.
829
1.68k
      const unsigned DestSize = DestTy->getScalarSizeInBits();
830
1.68k
      if (Cst->getValue().ult(DestSize)) {
831
1.68k
        Value *NewTrunc = Builder.CreateTrunc(A, DestTy, A->getName() + ".tr");
832
1.68k
833
1.68k
        return BinaryOperator::Create(
834
1.68k
          Instruction::Shl, NewTrunc,
835
1.68k
          ConstantInt::get(DestTy, Cst->getValue().trunc(DestSize)));
836
1.68k
      }
837
1.26M
    }
838
473k
  }
839
1.26M
840
1.26M
  if (Instruction *I = foldVecTruncToExtElt(CI, *this))
841
37
    return I;
842
1.26M
843
1.26M
  return nullptr;
844
1.26M
}
845
846
Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, ZExtInst &CI,
847
145k
                                             bool DoTransform) {
848
145k
  // If we are just checking for a icmp eq of a single bit and zext'ing it
849
145k
  // to an integer, then shift the bit to the appropriate place and then
850
145k
  // cast to integer to avoid the comparison.
851
145k
  const APInt *Op1CV;
852
145k
  if (match(ICI->getOperand(1), m_APInt(Op1CV))) {
853
115k
854
115k
    // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
855
115k
    // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
856
115k
    if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && 
Op1CV->isNullValue()3.61k
) ||
857
115k
        
(115k
ICI->getPredicate() == ICmpInst::ICMP_SGT115k
&&
Op1CV->isAllOnesValue()20.9k
)) {
858
207
      if (!DoTransform) 
return ICI8
;
859
199
860
199
      Value *In = ICI->getOperand(0);
861
199
      Value *Sh = ConstantInt::get(In->getType(),
862
199
                                   In->getType()->getScalarSizeInBits() - 1);
863
199
      In = Builder.CreateLShr(In, Sh, In->getName() + ".lobit");
864
199
      if (In->getType() != CI.getType())
865
82
        In = Builder.CreateIntCast(In, CI.getType(), false /*ZExt*/);
866
199
867
199
      if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
868
55
        Constant *One = ConstantInt::get(In->getType(), 1);
869
55
        In = Builder.CreateXor(In, One, In->getName() + ".not");
870
55
      }
871
199
872
199
      return replaceInstUsesWith(CI, In);
873
199
    }
874
115k
875
115k
    // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
876
115k
    // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
877
115k
    // zext (X == 1) to i32 --> X        iff X has only the low bit set.
878
115k
    // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
879
115k
    // zext (X != 0) to i32 --> X        iff X has only the low bit set.
880
115k
    // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
881
115k
    // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
882
115k
    // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
883
115k
    if ((Op1CV->isNullValue() || 
Op1CV->isPowerOf2()64.4k
) &&
884
115k
        // This only works for EQ and NE
885
115k
        
ICI->isEquality()63.2k
) {
886
53.2k
      // If Op1C some other power of two, convert:
887
53.2k
      KnownBits Known = computeKnownBits(ICI->getOperand(0), 0, &CI);
888
53.2k
889
53.2k
      APInt KnownZeroMask(~Known.Zero);
890
53.2k
      if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
891
2.44k
        if (!DoTransform) 
return ICI2
;
892
2.44k
893
2.44k
        bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
894
2.44k
        if (!Op1CV->isNullValue() && 
(*Op1CV != KnownZeroMask)7
) {
895
1
          // (X&4) == 2 --> false
896
1
          // (X&4) != 2 --> true
897
1
          Constant *Res = ConstantInt::get(CI.getType(), isNE);
898
1
          return replaceInstUsesWith(CI, Res);
899
1
        }
900
2.44k
901
2.44k
        uint32_t ShAmt = KnownZeroMask.logBase2();
902
2.44k
        Value *In = ICI->getOperand(0);
903
2.44k
        if (ShAmt) {
904
569
          // Perform a logical shr by shiftamt.
905
569
          // Insert the shift to put the result in the low bit.
906
569
          In = Builder.CreateLShr(In, ConstantInt::get(In->getType(), ShAmt),
907
569
                                  In->getName() + ".lobit");
908
569
        }
909
2.44k
910
2.44k
        if (!Op1CV->isNullValue() == isNE) { // Toggle the low bit.
911
444
          Constant *One = ConstantInt::get(In->getType(), 1);
912
444
          In = Builder.CreateXor(In, One);
913
444
        }
914
2.44k
915
2.44k
        if (CI.getType() == In->getType())
916
1.14k
          return replaceInstUsesWith(CI, In);
917
1.30k
918
1.30k
        Value *IntCast = Builder.CreateIntCast(In, CI.getType(), false);
919
1.30k
        return replaceInstUsesWith(CI, IntCast);
920
1.30k
      }
921
53.2k
    }
922
115k
  }
923
142k
924
142k
  // icmp ne A, B is equal to xor A, B when A and B only really have one bit.
925
142k
  // It is also profitable to transform icmp eq into not(xor(A, B)) because that
926
142k
  // may lead to additional simplifications.
927
142k
  if (ICI->isEquality() && 
CI.getType() == ICI->getOperand(0)->getType()96.6k
) {
928
62.5k
    if (IntegerType *ITy = dyn_cast<IntegerType>(CI.getType())) {
929
62.0k
      Value *LHS = ICI->getOperand(0);
930
62.0k
      Value *RHS = ICI->getOperand(1);
931
62.0k
932
62.0k
      KnownBits KnownLHS = computeKnownBits(LHS, 0, &CI);
933
62.0k
      KnownBits KnownRHS = computeKnownBits(RHS, 0, &CI);
934
62.0k
935
62.0k
      if (KnownLHS.Zero == KnownRHS.Zero && 
KnownLHS.One == KnownRHS.One4.79k
) {
936
4.47k
        APInt KnownBits = KnownLHS.Zero | KnownLHS.One;
937
4.47k
        APInt UnknownBit = ~KnownBits;
938
4.47k
        if (UnknownBit.countPopulation() == 1) {
939
3
          if (!DoTransform) 
return ICI0
;
940
3
941
3
          Value *Result = Builder.CreateXor(LHS, RHS);
942
3
943
3
          // Mask off any bits that are set and won't be shifted away.
944
3
          if (KnownLHS.One.uge(UnknownBit))
945
1
            Result = Builder.CreateAnd(Result,
946
1
                                        ConstantInt::get(ITy, UnknownBit));
947
3
948
3
          // Shift the bit we're testing down to the lsb.
949
3
          Result = Builder.CreateLShr(
950
3
               Result, ConstantInt::get(ITy, UnknownBit.countTrailingZeros()));
951
3
952
3
          if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
953
1
            Result = Builder.CreateXor(Result, ConstantInt::get(ITy, 1));
954
3
          Result->takeName(ICI);
955
3
          return replaceInstUsesWith(CI, Result);
956
3
        }
957
4.47k
      }
958
62.0k
    }
959
62.5k
  }
960
142k
961
142k
  return nullptr;
962
142k
}
963
964
/// Determine if the specified value can be computed in the specified wider type
965
/// and produce the same low bits. If not, return false.
966
///
967
/// If this function returns true, it can also return a non-zero number of bits
968
/// (in BitsToClear) which indicates that the value it computes is correct for
969
/// the zero extend, but that the additional BitsToClear bits need to be zero'd
970
/// out.  For example, to promote something like:
971
///
972
///   %B = trunc i64 %A to i32
973
///   %C = lshr i32 %B, 8
974
///   %E = zext i32 %C to i64
975
///
976
/// CanEvaluateZExtd for the 'lshr' will return true, and BitsToClear will be
977
/// set to 8 to indicate that the promoted value needs to have bits 24-31
978
/// cleared in addition to bits 32-63.  Since an 'and' will be generated to
979
/// clear the top bits anyway, doing this has no extra cost.
980
///
981
/// This function works on both vectors and scalars.
982
static bool canEvaluateZExtd(Value *V, Type *Ty, unsigned &BitsToClear,
983
2.05M
                             InstCombiner &IC, Instruction *CxtI) {
984
2.05M
  BitsToClear = 0;
985
2.05M
  if (canAlwaysEvaluateInType(V, Ty))
986
91.8k
    return true;
987
1.96M
  if (canNotEvaluateInType(V, Ty))
988
1.02M
    return false;
989
943k
990
943k
  auto *I = cast<Instruction>(V);
991
943k
  unsigned Tmp;
992
943k
  switch (I->getOpcode()) {
993
943k
  case Instruction::ZExt:  // zext(zext(x)) -> zext(x).
994
2.41k
  case Instruction::SExt:  // zext(sext(x)) -> sext(x).
995
2.41k
  case Instruction::Trunc: // zext(trunc(x)) -> trunc(x) or zext(x)
996
2.41k
    return true;
997
277k
  case Instruction::And:
998
277k
  case Instruction::Or:
999
277k
  case Instruction::Xor:
1000
277k
  case Instruction::Add:
1001
277k
  case Instruction::Sub:
1002
277k
  case Instruction::Mul:
1003
277k
    if (!canEvaluateZExtd(I->getOperand(0), Ty, BitsToClear, IC, CxtI) ||
1004
277k
        
!canEvaluateZExtd(I->getOperand(1), Ty, Tmp, IC, CxtI)79.1k
)
1005
274k
      return false;
1006
3.10k
    // These can all be promoted if neither operand has 'bits to clear'.
1007
3.10k
    if (BitsToClear == 0 && 
Tmp == 02.57k
)
1008
2.57k
      return true;
1009
524
1010
524
    // If the operation is an AND/OR/XOR and the bits to clear are zero in the
1011
524
    // other side, BitsToClear is ok.
1012
524
    if (Tmp == 0 && 
I->isBitwiseLogicOp()523
) {
1013
302
      // We use MaskedValueIsZero here for generality, but the case we care
1014
302
      // about the most is constant RHS.
1015
302
      unsigned VSize = V->getType()->getScalarSizeInBits();
1016
302
      if (IC.MaskedValueIsZero(I->getOperand(1),
1017
302
                               APInt::getHighBitsSet(VSize, BitsToClear),
1018
302
                               0, CxtI)) {
1019
296
        // If this is an And instruction and all of the BitsToClear are
1020
296
        // known to be zero we can reset BitsToClear.
1021
296
        if (I->getOpcode() == Instruction::And)
1022
294
          BitsToClear = 0;
1023
296
        return true;
1024
296
      }
1025
228
    }
1026
228
1027
228
    // Otherwise, we don't know how to analyze this BitsToClear case yet.
1028
228
    return false;
1029
228
1030
10.9k
  case Instruction::Shl: {
1031
10.9k
    // We can promote shl(x, cst) if we can promote x.  Since shl overwrites the
1032
10.9k
    // upper bits we can reduce BitsToClear by the shift amount.
1033
10.9k
    const APInt *Amt;
1034
10.9k
    if (match(I->getOperand(1), m_APInt(Amt))) {
1035
8.39k
      if (!canEvaluateZExtd(I->getOperand(0), Ty, BitsToClear, IC, CxtI))
1036
7.74k
        return false;
1037
644
      uint64_t ShiftAmt = Amt->getZExtValue();
1038
644
      BitsToClear = ShiftAmt < BitsToClear ? 
BitsToClear - ShiftAmt10
:
0634
;
1039
644
      return true;
1040
644
    }
1041
2.51k
    return false;
1042
2.51k
  }
1043
38.3k
  case Instruction::LShr: {
1044
38.3k
    // We can promote lshr(x, cst) if we can promote x.  This requires the
1045
38.3k
    // ultimate 'and' to clear out the high zero bits we're clearing out though.
1046
38.3k
    const APInt *Amt;
1047
38.3k
    if (match(I->getOperand(1), m_APInt(Amt))) {
1048
35.9k
      if (!canEvaluateZExtd(I->getOperand(0), Ty, BitsToClear, IC, CxtI))
1049
35.3k
        return false;
1050
646
      BitsToClear += Amt->getZExtValue();
1051
646
      if (BitsToClear > V->getType()->getScalarSizeInBits())
1052
0
        BitsToClear = V->getType()->getScalarSizeInBits();
1053
646
      return true;
1054
646
    }
1055
2.35k
    // Cannot promote variable LSHR.
1056
2.35k
    return false;
1057
2.35k
  }
1058
55.4k
  case Instruction::Select:
1059
55.4k
    if (!canEvaluateZExtd(I->getOperand(1), Ty, Tmp, IC, CxtI) ||
1060
55.4k
        
!canEvaluateZExtd(I->getOperand(2), Ty, BitsToClear, IC, CxtI)2.04k
||
1061
55.4k
        // TODO: If important, we could handle the case when the BitsToClear are
1062
55.4k
        // known zero in the disagreeing side.
1063
55.4k
        
Tmp != BitsToClear174
)
1064
55.2k
      return false;
1065
174
    return true;
1066
174
1067
19.0k
  case Instruction::PHI: {
1068
19.0k
    // We can change a phi if we can change all operands.  Note that we never
1069
19.0k
    // get into trouble with cyclic PHIs here because we only consider
1070
19.0k
    // instructions with a single use.
1071
19.0k
    PHINode *PN = cast<PHINode>(I);
1072
19.0k
    if (!canEvaluateZExtd(PN->getIncomingValue(0), Ty, BitsToClear, IC, CxtI))
1073
13.3k
      return false;
1074
7.71k
    
for (unsigned i = 1, e = PN->getNumIncomingValues(); 5.73k
i != e;
++i1.97k
)
1075
7.28k
      if (!canEvaluateZExtd(PN->getIncomingValue(i), Ty, Tmp, IC, CxtI) ||
1076
7.28k
          // TODO: If important, we could handle the case when the BitsToClear
1077
7.28k
          // are known zero in the disagreeing input.
1078
7.28k
          
Tmp != BitsToClear1.97k
)
1079
5.30k
        return false;
1080
5.73k
    
return true432
;
1081
5.73k
  }
1082
540k
  default:
1083
540k
    // TODO: Can handle more cases here.
1084
540k
    return false;
1085
943k
  }
1086
943k
}
1087
1088
1.73M
Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
1089
1.73M
  // If this zero extend is only used by a truncate, let the truncate be
1090
1.73M
  // eliminated before we try to optimize this zext.
1091
1.73M
  if (CI.hasOneUse() && 
isa<TruncInst>(CI.user_back())1.47M
)
1092
4.24k
    return nullptr;
1093
1.73M
1094
1.73M
  // If one of the common conversion will work, do it.
1095
1.73M
  if (Instruction *Result = commonCastTransforms(CI))
1096
2.47k
    return Result;
1097
1.73M
1098
1.73M
  Value *Src = CI.getOperand(0);
1099
1.73M
  Type *SrcTy = Src->getType(), *DestTy = CI.getType();
1100
1.73M
1101
1.73M
  // Try to extend the entire expression tree to the wide destination type.
1102
1.73M
  unsigned BitsToClear;
1103
1.73M
  if (shouldChangeType(SrcTy, DestTy) &&
1104
1.73M
      
canEvaluateZExtd(Src, DestTy, BitsToClear, *this, &CI)1.57M
) {
1105
5.55k
    assert(BitsToClear <= SrcTy->getScalarSizeInBits() &&
1106
5.55k
           "Can't clear more bits than in SrcTy");
1107
5.55k
1108
5.55k
    // Okay, we can transform this!  Insert the new expression now.
1109
5.55k
    LLVM_DEBUG(
1110
5.55k
        dbgs() << "ICE: EvaluateInDifferentType converting expression type"
1111
5.55k
                  " to avoid zero extend: "
1112
5.55k
               << CI << '\n');
1113
5.55k
    Value *Res = EvaluateInDifferentType(Src, DestTy, false);
1114
5.55k
    assert(Res->getType() == DestTy);
1115
5.55k
1116
5.55k
    // Preserve debug values referring to Src if the zext is its last use.
1117
5.55k
    if (auto *SrcOp = dyn_cast<Instruction>(Src))
1118
5.55k
      if (SrcOp->hasOneUse())
1119
4.07k
        replaceAllDbgUsesWith(*SrcOp, *Res, CI, DT);
1120
5.55k
1121
5.55k
    uint32_t SrcBitsKept = SrcTy->getScalarSizeInBits()-BitsToClear;
1122
5.55k
    uint32_t DestBitSize = DestTy->getScalarSizeInBits();
1123
5.55k
1124
5.55k
    // If the high bits are already filled with zeros, just replace this
1125
5.55k
    // cast with the result.
1126
5.55k
    if (MaskedValueIsZero(Res,
1127
5.55k
                          APInt::getHighBitsSet(DestBitSize,
1128
5.55k
                                                DestBitSize-SrcBitsKept),
1129
5.55k
                             0, &CI))
1130
2.17k
      return replaceInstUsesWith(CI, Res);
1131
3.38k
1132
3.38k
    // We need to emit an AND to clear the high bits.
1133
3.38k
    Constant *C = ConstantInt::get(Res->getType(),
1134
3.38k
                               APInt::getLowBitsSet(DestBitSize, SrcBitsKept));
1135
3.38k
    return BinaryOperator::CreateAnd(Res, C);
1136
3.38k
  }
1137
1.72M
1138
1.72M
  // If this is a TRUNC followed by a ZEXT then we are dealing with integral
1139
1.72M
  // types and if the sizes are just right we can convert this into a logical
1140
1.72M
  // 'and' which will be much cheaper than the pair of casts.
1141
1.72M
  if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) {   // A->B->C cast
1142
615
    // TODO: Subsume this into EvaluateInDifferentType.
1143
615
1144
615
    // Get the sizes of the types involved.  We know that the intermediate type
1145
615
    // will be smaller than A or C, but don't know the relation between A and C.
1146
615
    Value *A = CSrc->getOperand(0);
1147
615
    unsigned SrcSize = A->getType()->getScalarSizeInBits();
1148
615
    unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
1149
615
    unsigned DstSize = CI.getType()->getScalarSizeInBits();
1150
615
    // If we're actually extending zero bits, then if
1151
615
    // SrcSize <  DstSize: zext(a & mask)
1152
615
    // SrcSize == DstSize: a & mask
1153
615
    // SrcSize  > DstSize: trunc(a) & mask
1154
615
    if (SrcSize < DstSize) {
1155
38
      APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
1156
38
      Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
1157
38
      Value *And = Builder.CreateAnd(A, AndConst, CSrc->getName() + ".mask");
1158
38
      return new ZExtInst(And, CI.getType());
1159
38
    }
1160
577
1161
577
    if (SrcSize == DstSize) {
1162
482
      APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
1163
482
      return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
1164
482
                                                           AndValue));
1165
482
    }
1166
95
    if (SrcSize > DstSize) {
1167
95
      Value *Trunc = Builder.CreateTrunc(A, CI.getType());
1168
95
      APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
1169
95
      return BinaryOperator::CreateAnd(Trunc,
1170
95
                                       ConstantInt::get(Trunc->getType(),
1171
95
                                                        AndValue));
1172
95
    }
1173
1.72M
  }
1174
1.72M
1175
1.72M
  if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
1176
142k
    return transformZExtICmp(ICI, CI);
1177
1.58M
1178
1.58M
  BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
1179
1.58M
  if (SrcI && 
SrcI->getOpcode() == Instruction::Or366k
) {
1180
16.7k
    // zext (or icmp, icmp) -> or (zext icmp), (zext icmp) if at least one
1181
16.7k
    // of the (zext icmp) can be eliminated. If so, immediately perform the
1182
16.7k
    // according elimination.
1183
16.7k
    ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
1184
16.7k
    ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
1185
16.7k
    if (LHS && 
RHS1.58k
&&
LHS->hasOneUse()1.40k
&&
RHS->hasOneUse()1.29k
&&
1186
16.7k
        
(1.21k
transformZExtICmp(LHS, CI, false)1.21k
||
1187
1.21k
         
transformZExtICmp(RHS, CI, false)1.21k
)) {
1188
10
      // zext (or icmp, icmp) -> or (zext icmp), (zext icmp)
1189
10
      Value *LCast = Builder.CreateZExt(LHS, CI.getType(), LHS->getName());
1190
10
      Value *RCast = Builder.CreateZExt(RHS, CI.getType(), RHS->getName());
1191
10
      BinaryOperator *Or = BinaryOperator::Create(Instruction::Or, LCast, RCast);
1192
10
1193
10
      // Perform the elimination.
1194
10
      if (auto *LZExt = dyn_cast<ZExtInst>(LCast))
1195
10
        transformZExtICmp(LHS, *LZExt);
1196
10
      if (auto *RZExt = dyn_cast<ZExtInst>(RCast))
1197
10
        transformZExtICmp(RHS, *RZExt);
1198
10
1199
10
      return Or;
1200
10
    }
1201
1.58M
  }
1202
1.58M
1203
1.58M
  // zext(trunc(X) & C) -> (X & zext(C)).
1204
1.58M
  Constant *C;
1205
1.58M
  Value *X;
1206
1.58M
  if (SrcI &&
1207
1.58M
      
match(SrcI, m_OneUse(m_And(m_Trunc(m_Value(X)), m_Constant(C))))365k
&&
1208
1.58M
      
X->getType() == CI.getType()85
)
1209
69
    return BinaryOperator::CreateAnd(X, ConstantExpr::getZExt(C, CI.getType()));
1210
1.58M
1211
1.58M
  // zext((trunc(X) & C) ^ C) -> ((X & zext(C)) ^ zext(C)).
1212
1.58M
  Value *And;
1213
1.58M
  if (SrcI && 
match(SrcI, m_OneUse(m_Xor(m_Value(And), m_Constant(C))))365k
&&
1214
1.58M
      
match(And, m_OneUse(m_And(m_Trunc(m_Value(X)), m_Specific(C))))20.0k
&&
1215
1.58M
      
X->getType() == CI.getType()1
) {
1216
1
    Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
1217
1
    return BinaryOperator::CreateXor(Builder.CreateAnd(X, ZC), ZC);
1218
1
  }
1219
1.58M
1220
1.58M
  return nullptr;
1221
1.58M
}
1222
1223
/// Transform (sext icmp) to bitwise / integer operations to eliminate the icmp.
1224
4.63k
Instruction *InstCombiner::transformSExtICmp(ICmpInst *ICI, Instruction &CI) {
1225
4.63k
  Value *Op0 = ICI->getOperand(0), *Op1 = ICI->getOperand(1);
1226
4.63k
  ICmpInst::Predicate Pred = ICI->getPredicate();
1227
4.63k
1228
4.63k
  // Don't bother if Op1 isn't of vector or integer type.
1229
4.63k
  if (!Op1->getType()->isIntOrIntVectorTy())
1230
84
    return nullptr;
1231
4.55k
1232
4.55k
  if ((Pred == ICmpInst::ICMP_SLT && 
match(Op1, m_ZeroInt())726
) ||
1233
4.55k
      
(4.50k
Pred == ICmpInst::ICMP_SGT4.50k
&&
match(Op1, m_AllOnes())775
)) {
1234
86
    // (x <s  0) ? -1 : 0 -> ashr x, 31        -> all ones if negative
1235
86
    // (x >s -1) ? -1 : 0 -> not (ashr x, 31)  -> all ones if positive
1236
86
    Value *Sh = ConstantInt::get(Op0->getType(),
1237
86
                                 Op0->getType()->getScalarSizeInBits() - 1);
1238
86
    Value *In = Builder.CreateAShr(Op0, Sh, Op0->getName() + ".lobit");
1239
86
    if (In->getType() != CI.getType())
1240
7
      In = Builder.CreateIntCast(In, CI.getType(), true /*SExt*/);
1241
86
1242
86
    if (Pred == ICmpInst::ICMP_SGT)
1243
38
      In = Builder.CreateNot(In, In->getName() + ".not");
1244
86
    return replaceInstUsesWith(CI, In);
1245
86
  }
1246
4.46k
1247
4.46k
  if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
1248
1.57k
    // If we know that only one bit of the LHS of the icmp can be set and we
1249
1.57k
    // have an equality comparison with zero or a power of 2, we can transform
1250
1.57k
    // the icmp and sext into bitwise/integer operations.
1251
1.57k
    if (ICI->hasOneUse() &&
1252
1.57k
        
ICI->isEquality()1.29k
&&
(680
Op1C->isZero()680
||
Op1C->getValue().isPowerOf2()289
)){
1253
556
      KnownBits Known = computeKnownBits(Op0, 0, &CI);
1254
556
1255
556
      APInt KnownZeroMask(~Known.Zero);
1256
556
      if (KnownZeroMask.isPowerOf2()) {
1257
54
        Value *In = ICI->getOperand(0);
1258
54
1259
54
        // If the icmp tests for a known zero bit we can constant fold it.
1260
54
        if (!Op1C->isZero() && 
Op1C->getValue() != KnownZeroMask0
) {
1261
0
          Value *V = Pred == ICmpInst::ICMP_NE ?
1262
0
                       ConstantInt::getAllOnesValue(CI.getType()) :
1263
0
                       ConstantInt::getNullValue(CI.getType());
1264
0
          return replaceInstUsesWith(CI, V);
1265
0
        }
1266
54
1267
54
        if (!Op1C->isZero() == (Pred == ICmpInst::ICMP_NE)) {
1268
17
          // sext ((x & 2^n) == 0)   -> (x >> n) - 1
1269
17
          // sext ((x & 2^n) != 2^n) -> (x >> n) - 1
1270
17
          unsigned ShiftAmt = KnownZeroMask.countTrailingZeros();
1271
17
          // Perform a right shift to place the desired bit in the LSB.
1272
17
          if (ShiftAmt)
1273
8
            In = Builder.CreateLShr(In,
1274
8
                                    ConstantInt::get(In->getType(), ShiftAmt));
1275
17
1276
17
          // At this point "In" is either 1 or 0. Subtract 1 to turn
1277
17
          // {1, 0} -> {0, -1}.
1278
17
          In = Builder.CreateAdd(In,
1279
17
                                 ConstantInt::getAllOnesValue(In->getType()),
1280
17
                                 "sext");
1281
37
        } else {
1282
37
          // sext ((x & 2^n) != 0)   -> (x << bitwidth-n) a>> bitwidth-1
1283
37
          // sext ((x & 2^n) == 2^n) -> (x << bitwidth-n) a>> bitwidth-1
1284
37
          unsigned ShiftAmt = KnownZeroMask.countLeadingZeros();
1285
37
          // Perform a left shift to place the desired bit in the MSB.
1286
37
          if (ShiftAmt)
1287
37
            In = Builder.CreateShl(In,
1288
37
                                   ConstantInt::get(In->getType(), ShiftAmt));
1289
37
1290
37
          // Distribute the bit over the whole bit width.
1291
37
          In = Builder.CreateAShr(In, ConstantInt::get(In->getType(),
1292
37
                                  KnownZeroMask.getBitWidth() - 1), "sext");
1293
37
        }
1294
54
1295
54
        if (CI.getType() == In->getType())
1296
10
          return replaceInstUsesWith(CI, In);
1297
44
        return CastInst::CreateIntegerCast(In, CI.getType(), true/*SExt*/);
1298
44
      }
1299
556
    }
1300
1.57k
  }
1301
4.41k
1302
4.41k
  return nullptr;
1303
4.41k
}
1304
1305
/// Return true if we can take the specified value and return it as type Ty
1306
/// without inserting any new casts and without changing the value of the common
1307
/// low bits.  This is used by code that tries to promote integer operations to
1308
/// a wider types will allow us to eliminate the extension.
1309
///
1310
/// This function works on both vectors and scalars.
1311
///
1312
2.47M
static bool canEvaluateSExtd(Value *V, Type *Ty) {
1313
2.47M
  assert(V->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits() &&
1314
2.47M
         "Can't sign extend type to a smaller type");
1315
2.47M
  if (canAlwaysEvaluateInType(V, Ty))
1316
26.3k
    return true;
1317
2.44M
  if (canNotEvaluateInType(V, Ty))
1318
1.36M
    return false;
1319
1.07M
1320
1.07M
  auto *I = cast<Instruction>(V);
1321
1.07M
  switch (I->getOpcode()) {
1322
1.07M
  case Instruction::SExt:  // sext(sext(x)) -> sext(x)
1323
1.79k
  case Instruction::ZExt:  // sext(zext(x)) -> zext(x)
1324
1.79k
  case Instruction::Trunc: // sext(trunc(x)) -> trunc(x) or sext(x)
1325
1.79k
    return true;
1326
403k
  case Instruction::And:
1327
403k
  case Instruction::Or:
1328
403k
  case Instruction::Xor:
1329
403k
  case Instruction::Add:
1330
403k
  case Instruction::Sub:
1331
403k
  case Instruction::Mul:
1332
403k
    // These operators can all arbitrarily be extended if their inputs can.
1333
403k
    return canEvaluateSExtd(I->getOperand(0), Ty) &&
1334
403k
           
canEvaluateSExtd(I->getOperand(1), Ty)20.2k
;
1335
403k
1336
403k
  //case Instruction::Shl:   TODO
1337
403k
  //case Instruction::LShr:  TODO
1338
403k
1339
403k
  case Instruction::Select:
1340
7.17k
    return canEvaluateSExtd(I->getOperand(1), Ty) &&
1341
7.17k
           
canEvaluateSExtd(I->getOperand(2), Ty)956
;
1342
403k
1343
403k
  case Instruction::PHI: {
1344
41.3k
    // We can change a phi if we can change all operands.  Note that we never
1345
41.3k
    // get into trouble with cyclic PHIs here because we only consider
1346
41.3k
    // instructions with a single use.
1347
41.3k
    PHINode *PN = cast<PHINode>(I);
1348
41.3k
    for (Value *IncValue : PN->incoming_values())
1349
45.0k
      if (!canEvaluateSExtd(IncValue, Ty)) 
return false41.0k
;
1350
41.3k
    
return true279
;
1351
41.3k
  }
1352
626k
  default:
1353
626k
    // TODO: Can handle more cases here.
1354
626k
    break;
1355
626k
  }
1356
626k
1357
626k
  return false;
1358
626k
}
1359
1360
2.04M
Instruction *InstCombiner::visitSExt(SExtInst &CI) {
1361
2.04M
  // If this sign extend is only used by a truncate, let the truncate be
1362
2.04M
  // eliminated before we try to optimize this sext.
1363
2.04M
  if (CI.hasOneUse() && 
isa<TruncInst>(CI.user_back())1.71M
)
1364
224
    return nullptr;
1365
2.04M
1366
2.04M
  if (Instruction *I = commonCastTransforms(CI))
1367
4.25k
    return I;
1368
2.03M
1369
2.03M
  Value *Src = CI.getOperand(0);
1370
2.03M
  Type *SrcTy = Src->getType(), *DestTy = CI.getType();
1371
2.03M
1372
2.03M
  // If we know that the value being extended is positive, we can use a zext
1373
2.03M
  // instead.
1374
2.03M
  KnownBits Known = computeKnownBits(Src, 0, &CI);
1375
2.03M
  if (Known.isNonNegative())
1376
26.6k
    return CastInst::Create(Instruction::ZExt, Src, DestTy);
1377
2.01M
1378
2.01M
  // Try to extend the entire expression tree to the wide destination type.
1379
2.01M
  if (shouldChangeType(SrcTy, DestTy) && 
canEvaluateSExtd(Src, DestTy)1.99M
) {
1380
3.14k
    // Okay, we can transform this!  Insert the new expression now.
1381
3.14k
    LLVM_DEBUG(
1382
3.14k
        dbgs() << "ICE: EvaluateInDifferentType converting expression type"
1383
3.14k
                  " to avoid sign extend: "
1384
3.14k
               << CI << '\n');
1385
3.14k
    Value *Res = EvaluateInDifferentType(Src, DestTy, true);
1386
3.14k
    assert(Res->getType() == DestTy);
1387
3.14k
1388
3.14k
    uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
1389
3.14k
    uint32_t DestBitSize = DestTy->getScalarSizeInBits();
1390
3.14k
1391
3.14k
    // If the high bits are already filled with sign bit, just replace this
1392
3.14k
    // cast with the result.
1393
3.14k
    if (ComputeNumSignBits(Res, 0, &CI) > DestBitSize - SrcBitSize)
1394
412
      return replaceInstUsesWith(CI, Res);
1395
2.73k
1396
2.73k
    // We need to emit a shl + ashr to do the sign extend.
1397
2.73k
    Value *ShAmt = ConstantInt::get(DestTy, DestBitSize-SrcBitSize);
1398
2.73k
    return BinaryOperator::CreateAShr(Builder.CreateShl(Res, ShAmt, "sext"),
1399
2.73k
                                      ShAmt);
1400
2.73k
  }
1401
2.00M
1402
2.00M
  // If the input is a trunc from the destination type, then turn sext(trunc(x))
1403
2.00M
  // into shifts.
1404
2.00M
  Value *X;
1405
2.00M
  if (match(Src, m_OneUse(m_Trunc(m_Value(X)))) && 
X->getType() == DestTy16
) {
1406
5
    // sext(trunc(X)) --> ashr(shl(X, C), C)
1407
5
    unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1408
5
    unsigned DestBitSize = DestTy->getScalarSizeInBits();
1409
5
    Constant *ShAmt = ConstantInt::get(DestTy, DestBitSize - SrcBitSize);
1410
5
    return BinaryOperator::CreateAShr(Builder.CreateShl(X, ShAmt), ShAmt);
1411
5
  }
1412
2.00M
1413
2.00M
  if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
1414
4.63k
    return transformSExtICmp(ICI, CI);
1415
2.00M
1416
2.00M
  // If the input is a shl/ashr pair of a same constant, then this is a sign
1417
2.00M
  // extension from a smaller value.  If we could trust arbitrary bitwidth
1418
2.00M
  // integers, we could turn this into a truncate to the smaller bit and then
1419
2.00M
  // use a sext for the whole extension.  Since we don't, look deeper and check
1420
2.00M
  // for a truncate.  If the source and dest are the same type, eliminate the
1421
2.00M
  // trunc and extend and just do shifts.  For example, turn:
1422
2.00M
  //   %a = trunc i32 %i to i8
1423
2.00M
  //   %b = shl i8 %a, 6
1424
2.00M
  //   %c = ashr i8 %b, 6
1425
2.00M
  //   %d = sext i8 %c to i32
1426
2.00M
  // into:
1427
2.00M
  //   %a = shl i32 %i, 30
1428
2.00M
  //   %d = ashr i32 %a, 30
1429
2.00M
  Value *A = nullptr;
1430
2.00M
  // TODO: Eventually this could be subsumed by EvaluateInDifferentType.
1431
2.00M
  ConstantInt *BA = nullptr, *CA = nullptr;
1432
2.00M
  if (match(Src, m_AShr(m_Shl(m_Trunc(m_Value(A)), m_ConstantInt(BA)),
1433
2.00M
                        m_ConstantInt(CA))) &&
1434
2.00M
      
BA == CA3
&&
A->getType() == CI.getType()3
) {
1435
3
    unsigned MidSize = Src->getType()->getScalarSizeInBits();
1436
3
    unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
1437
3
    unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
1438
3
    Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
1439
3
    A = Builder.CreateShl(A, ShAmtV, CI.getName());
1440
3
    return BinaryOperator::CreateAShr(A, ShAmtV);
1441
3
  }
1442
2.00M
1443
2.00M
  return nullptr;
1444
2.00M
}
1445
1446
1447
/// Return a Constant* for the specified floating-point constant if it fits
1448
/// in the specified FP type without changing its value.
1449
5.33k
static bool fitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
1450
5.33k
  bool losesInfo;
1451
5.33k
  APFloat F = CFP->getValueAPF();
1452
5.33k
  (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
1453
5.33k
  return !losesInfo;
1454
5.33k
}
1455
1456
3.96k
static Type *shrinkFPConstant(ConstantFP *CFP) {
1457
3.96k
  if (CFP->getType() == Type::getPPC_FP128Ty(CFP->getContext()))
1458
0
    return nullptr;  // No constant folding of this.
1459
3.96k
  // See if the value can be truncated to half and then reextended.
1460
3.96k
  if (fitsInFPType(CFP, APFloat::IEEEhalf()))
1461
2.59k
    return Type::getHalfTy(CFP->getContext());
1462
1.37k
  // See if the value can be truncated to float and then reextended.
1463
1.37k
  if (fitsInFPType(CFP, APFloat::IEEEsingle()))
1464
65
    return Type::getFloatTy(CFP->getContext());
1465
1.30k
  if (CFP->getType()->isDoubleTy())
1466
1.30k
    return nullptr;  // Won't shrink.
1467
0
  if (fitsInFPType(CFP, APFloat::IEEEdouble()))
1468
0
    return Type::getDoubleTy(CFP->getContext());
1469
0
  // Don't try to shrink to various long double types.
1470
0
  return nullptr;
1471
0
}
1472
1473
// Determine if this is a vector of ConstantFPs and if so, return the minimal
1474
// type we can safely truncate all elements to.
1475
// TODO: Make these support undef elements.
1476
95.5k
static Type *shrinkFPConstantVector(Value *V) {
1477
95.5k
  auto *CV = dyn_cast<Constant>(V);
1478
95.5k
  if (!CV || 
!CV->getType()->isVectorTy()1.48k
)
1479
95.2k
    return nullptr;
1480
279
1481
279
  Type *MinType = nullptr;
1482
279
1483
279
  unsigned NumElts = CV->getType()->getVectorNumElements();
1484
891
  for (unsigned i = 0; i != NumElts; 
++i612
) {
1485
719
    auto *CFP = dyn_cast_or_null<ConstantFP>(CV->getAggregateElement(i));
1486
719
    if (!CFP)
1487
2
      return nullptr;
1488
717
1489
717
    Type *T = shrinkFPConstant(CFP);
1490
717
    if (!T)
1491
105
      return nullptr;
1492
612
1493
612
    // If we haven't found a type yet or this type has a larger mantissa than
1494
612
    // our previous type, this is our new minimal type.
1495
612
    if (!MinType || 
T->getFPMantissaWidth() > MinType->getFPMantissaWidth()438
)
1496
175
      MinType = T;
1497
612
  }
1498
279
1499
279
  // Make a vector type from the minimal type.
1500
279
  
return VectorType::get(MinType, NumElts)172
;
1501
279
}
1502
1503
/// Find the minimum FP type we can safely truncate to.
1504
102k
static Type *getMinimumFPType(Value *V) {
1505
102k
  if (auto *FPExt = dyn_cast<FPExtInst>(V))
1506
4.60k
    return FPExt->getOperand(0)->getType();
1507
97.5k
1508
97.5k
  // If this value is a constant, return the constant in the smallest FP type
1509
97.5k
  // that can accurately represent it.  This allows us to turn
1510
97.5k
  // (float)((double)X+2.0) into x+2.0f.
1511
97.5k
  if (auto *CFP = dyn_cast<ConstantFP>(V))
1512
3.24k
    if (Type *T = shrinkFPConstant(CFP))
1513
2.04k
      return T;
1514
95.5k
1515
95.5k
  // Try to shrink a vector of FP constants.
1516
95.5k
  if (Type *T = shrinkFPConstantVector(V))
1517
172
    return T;
1518
95.3k
1519
95.3k
  return V->getType();
1520
95.3k
}
1521
1522
58.8k
Instruction *InstCombiner::visitFPTrunc(FPTruncInst &FPT) {
1523
58.8k
  if (Instruction *I = commonCastTransforms(FPT))
1524
512
    return I;
1525
58.3k
1526
58.3k
  // If we have fptrunc(OpI (fpextend x), (fpextend y)), we would like to
1527
58.3k
  // simplify this expression to avoid one or more of the trunc/extend
1528
58.3k
  // operations if we can do so without changing the numerical results.
1529
58.3k
  //
1530
58.3k
  // The exact manner in which the widths of the operands interact to limit
1531
58.3k
  // what we can and cannot do safely varies from operation to operation, and
1532
58.3k
  // is explained below in the various case statements.
1533
58.3k
  Type *Ty = FPT.getType();
1534
58.3k
  BinaryOperator *OpI = dyn_cast<BinaryOperator>(FPT.getOperand(0));
1535
58.3k
  if (OpI && 
OpI->hasOneUse()51.2k
) {
1536
51.0k
    Type *LHSMinType = getMinimumFPType(OpI->getOperand(0));
1537
51.0k
    Type *RHSMinType = getMinimumFPType(OpI->getOperand(1));
1538
51.0k
    unsigned OpWidth = OpI->getType()->getFPMantissaWidth();
1539
51.0k
    unsigned LHSWidth = LHSMinType->getFPMantissaWidth();
1540
51.0k
    unsigned RHSWidth = RHSMinType->getFPMantissaWidth();
1541
51.0k
    unsigned SrcWidth = std::max(LHSWidth, RHSWidth);
1542
51.0k
    unsigned DstWidth = Ty->getFPMantissaWidth();
1543
51.0k
    switch (OpI->getOpcode()) {
1544
51.0k
      
default: break0
;
1545
51.0k
      case Instruction::FAdd:
1546
3.76k
      case Instruction::FSub:
1547
3.76k
        // For addition and subtraction, the infinitely precise result can
1548
3.76k
        // essentially be arbitrarily wide; proving that double rounding
1549
3.76k
        // will not occur because the result of OpI is exact (as we will for
1550
3.76k
        // FMul, for example) is hopeless.  However, we *can* nonetheless
1551
3.76k
        // frequently know that double rounding cannot occur (or that it is
1552
3.76k
        // innocuous) by taking advantage of the specific structure of
1553
3.76k
        // infinitely-precise results that admit double rounding.
1554
3.76k
        //
1555
3.76k
        // Specifically, if OpWidth >= 2*DstWdith+1 and DstWidth is sufficient
1556
3.76k
        // to represent both sources, we can guarantee that the double
1557
3.76k
        // rounding is innocuous (See p50 of Figueroa's 2000 PhD thesis,
1558
3.76k
        // "A Rigorous Framework for Fully Supporting the IEEE Standard ..."
1559
3.76k
        // for proof of this fact).
1560
3.76k
        //
1561
3.76k
        // Note: Figueroa does not consider the case where DstFormat !=
1562
3.76k
        // SrcFormat.  It's possible (likely even!) that this analysis
1563
3.76k
        // could be tightened for those cases, but they are rare (the main
1564
3.76k
        // case of interest here is (float)((double)float + float)).
1565
3.76k
        if (OpWidth >= 2*DstWidth+1 && 
DstWidth >= SrcWidth3.75k
) {
1566
38
          Value *LHS = Builder.CreateFPTrunc(OpI->getOperand(0), Ty);
1567
38
          Value *RHS = Builder.CreateFPTrunc(OpI->getOperand(1), Ty);
1568
38
          Instruction *RI = BinaryOperator::Create(OpI->getOpcode(), LHS, RHS);
1569
38
          RI->copyFastMathFlags(OpI);
1570
38
          return RI;
1571
38
        }
1572
3.72k
        break;
1573
4.12k
      case Instruction::FMul:
1574
4.12k
        // For multiplication, the infinitely precise result has at most
1575
4.12k
        // LHSWidth + RHSWidth significant bits; if OpWidth is sufficient
1576
4.12k
        // that such a value can be exactly represented, then no double
1577
4.12k
        // rounding can possibly occur; we can safely perform the operation
1578
4.12k
        // in the destination format if it can represent both sources.
1579
4.12k
        if (OpWidth >= LHSWidth + RHSWidth && 
DstWidth >= SrcWidth24
) {
1580
24
          Value *LHS = Builder.CreateFPTrunc(OpI->getOperand(0), Ty);
1581
24
          Value *RHS = Builder.CreateFPTrunc(OpI->getOperand(1), Ty);
1582
24
          return BinaryOperator::CreateFMulFMF(LHS, RHS, OpI);
1583
24
        }
1584
4.10k
        break;
1585
43.1k
      case Instruction::FDiv:
1586
43.1k
        // For division, we use again use the bound from Figueroa's
1587
43.1k
        // dissertation.  I am entirely certain that this bound can be
1588
43.1k
        // tightened in the unbalanced operand case by an analysis based on
1589
43.1k
        // the diophantine rational approximation bound, but the well-known
1590
43.1k
        // condition used here is a good conservative first pass.
1591
43.1k
        // TODO: Tighten bound via rigorous analysis of the unbalanced case.
1592
43.1k
        if (OpWidth >= 2*DstWidth && 
DstWidth >= SrcWidth43.1k
) {
1593
135
          Value *LHS = Builder.CreateFPTrunc(OpI->getOperand(0), Ty);
1594
135
          Value *RHS = Builder.CreateFPTrunc(OpI->getOperand(1), Ty);
1595
135
          return BinaryOperator::CreateFDivFMF(LHS, RHS, OpI);
1596
135
        }
1597
43.0k
        break;
1598
43.0k
      case Instruction::FRem: {
1599
6
        // Remainder is straightforward.  Remainder is always exact, so the
1600
6
        // type of OpI doesn't enter into things at all.  We simply evaluate
1601
6
        // in whichever source type is larger, then convert to the
1602
6
        // destination type.
1603
6
        if (SrcWidth == OpWidth)
1604
3
          break;
1605
3
        Value *LHS, *RHS;
1606
3
        if (LHSWidth == SrcWidth) {
1607
2
           LHS = Builder.CreateFPTrunc(OpI->getOperand(0), LHSMinType);
1608
2
           RHS = Builder.CreateFPTrunc(OpI->getOperand(1), LHSMinType);
1609
2
        } else {
1610
1
           LHS = Builder.CreateFPTrunc(OpI->getOperand(0), RHSMinType);
1611
1
           RHS = Builder.CreateFPTrunc(OpI->getOperand(1), RHSMinType);
1612
1
        }
1613
3
1614
3
        Value *ExactResult = Builder.CreateFRemFMF(LHS, RHS, OpI);
1615
3
        return CastInst::CreateFPCast(ExactResult, Ty);
1616
3
      }
1617
51.0k
    }
1618
51.0k
  }
1619
58.1k
1620
58.1k
  // (fptrunc (fneg x)) -> (fneg (fptrunc x))
1621
58.1k
  Value *X;
1622
58.1k
  Instruction *Op = dyn_cast<Instruction>(FPT.getOperand(0));
1623
58.1k
  if (Op && 
Op->hasOneUse()57.4k
) {
1624
57.1k
    if (match(Op, m_FNeg(m_Value(X)))) {
1625
19
      Value *InnerTrunc = Builder.CreateFPTrunc(X, Ty);
1626
19
1627
19
      // FIXME: Once we're sure that unary FNeg optimizations are on par with
1628
19
      // binary FNeg, this should always return a unary operator.
1629
19
      if (isa<BinaryOperator>(Op))
1630
13
        return BinaryOperator::CreateFNegFMF(InnerTrunc, Op);
1631
6
      return UnaryOperator::CreateFNegFMF(InnerTrunc, Op);
1632
6
    }
1633
57.1k
  }
1634
58.1k
1635
58.1k
  if (auto *II = dyn_cast<IntrinsicInst>(FPT.getOperand(0))) {
1636
1.63k
    switch (II->getIntrinsicID()) {
1637
1.63k
    
default: break1.40k
;
1638
1.63k
    case Intrinsic::ceil:
1639
225
    case Intrinsic::fabs:
1640
225
    case Intrinsic::floor:
1641
225
    case Intrinsic::nearbyint:
1642
225
    case Intrinsic::rint:
1643
225
    case Intrinsic::round:
1644
225
    case Intrinsic::trunc: {
1645
225
      Value *Src = II->getArgOperand(0);
1646
225
      if (!Src->hasOneUse())
1647
49
        break;
1648
176
1649
176
      // Except for fabs, this transformation requires the input of the unary FP
1650
176
      // operation to be itself an fpext from the type to which we're
1651
176
      // truncating.
1652
176
      if (II->getIntrinsicID() != Intrinsic::fabs) {
1653
131
        FPExtInst *FPExtSrc = dyn_cast<FPExtInst>(Src);
1654
131
        if (!FPExtSrc || 
FPExtSrc->getSrcTy() != Ty52
)
1655
79
          break;
1656
97
      }
1657
97
1658
97
      // Do unary FP operation on smaller type.
1659
97
      // (fptrunc (fabs x)) -> (fabs (fptrunc x))
1660
97
      Value *InnerTrunc = Builder.CreateFPTrunc(Src, Ty);
1661
97
      Function *Overload = Intrinsic::getDeclaration(FPT.getModule(),
1662
97
                                                     II->getIntrinsicID(), Ty);
1663
97
      SmallVector<OperandBundleDef, 1> OpBundles;
1664
97
      II->getOperandBundlesAsDefs(OpBundles);
1665
97
      CallInst *NewCI =
1666
97
          CallInst::Create(Overload, {InnerTrunc}, OpBundles, II->getName());
1667
97
      NewCI->copyFastMathFlags(II);
1668
97
      return NewCI;
1669
97
    }
1670
1.63k
    }
1671
1.63k
  }
1672
58.0k
1673
58.0k
  if (Instruction *I = shrinkInsertElt(FPT, Builder))
1674
1
    return I;
1675
58.0k
1676
58.0k
  return nullptr;
1677
58.0k
}
1678
1679
177k
Instruction *InstCombiner::visitFPExt(CastInst &CI) {
1680
177k
  return commonCastTransforms(CI);
1681
177k
}
1682
1683
// fpto{s/u}i({u/s}itofp(X)) --> X or zext(X) or sext(X) or trunc(X)
1684
// This is safe if the intermediate type has enough bits in its mantissa to
1685
// accurately represent all values of X.  For example, this won't work with
1686
// i64 -> float -> i64.
1687
82.6k
Instruction *InstCombiner::FoldItoFPtoI(Instruction &FI) {
1688
82.6k
  if (!isa<UIToFPInst>(FI.getOperand(0)) && 
!isa<SIToFPInst>(FI.getOperand(0))82.5k
)
1689
82.4k
    return nullptr;
1690
136
  Instruction *OpI = cast<Instruction>(FI.getOperand(0));
1691
136
1692
136
  Value *SrcI = OpI->getOperand(0);
1693
136
  Type *FITy = FI.getType();
1694
136
  Type *OpITy = OpI->getType();
1695
136
  Type *SrcTy = SrcI->getType();
1696
136
  bool IsInputSigned = isa<SIToFPInst>(OpI);
1697
136
  bool IsOutputSigned = isa<FPToSIInst>(FI);
1698
136
1699
136
  // We can safely assume the conversion won't overflow the output range,
1700
136
  // because (for example) (uint8_t)18293.f is undefined behavior.
1701
136
1702
136
  // Since we can assume the conversion won't overflow, our decision as to
1703
136
  // whether the input will fit in the float should depend on the minimum
1704
136
  // of the input range and output range.
1705
136
1706
136
  // This means this is also safe for a signed input and unsigned output, since
1707
136
  // a negative input would lead to undefined behavior.
1708
136
  int InputSize = (int)SrcTy->getScalarSizeInBits() - IsInputSigned;
1709
136
  int OutputSize = (int)FITy->getScalarSizeInBits() - IsOutputSigned;
1710
136
  int ActualSize = std::min(InputSize, OutputSize);
1711
136
1712
136
  if (ActualSize <= OpITy->getFPMantissaWidth()) {
1713
18
    if (FITy->getScalarSizeInBits() > SrcTy->getScalarSizeInBits()) {
1714
8
      if (IsInputSigned && 
IsOutputSigned7
)
1715
4
        return new SExtInst(SrcI, FITy);
1716
4
      return new ZExtInst(SrcI, FITy);
1717
4
    }
1718
10
    if (FITy->getScalarSizeInBits() < SrcTy->getScalarSizeInBits())
1719
3
      return new TruncInst(SrcI, FITy);
1720
7
    if (SrcTy == FITy)
1721
7
      return replaceInstUsesWith(FI, SrcI);
1722
0
    return new BitCastInst(SrcI, FITy);
1723
0
  }
1724
118
  return nullptr;
1725
118
}
1726
1727
46.9k
Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
1728
46.9k
  Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
1729
46.9k
  if (!OpI)
1730
93
    return commonCastTransforms(FI);
1731
46.8k
1732
46.8k
  if (Instruction *I = FoldItoFPtoI(FI))
1733
7
    return I;
1734
46.8k
1735
46.8k
  return commonCastTransforms(FI);
1736
46.8k
}
1737
1738
36.2k
Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
1739
36.2k
  Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
1740
36.2k
  if (!OpI)
1741
490
    return commonCastTransforms(FI);
1742
35.7k
1743
35.7k
  if (Instruction *I = FoldItoFPtoI(FI))
1744
11
    return I;
1745
35.7k
1746
35.7k
  return commonCastTransforms(FI);
1747
35.7k
}
1748
1749
204k
Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
1750
204k
  return commonCastTransforms(CI);
1751
204k
}
1752
1753
285k
Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
1754
285k
  return commonCastTransforms(CI);
1755
285k
}
1756
1757
497k
Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
1758
497k
  // If the source integer type is not the intptr_t type for this target, do a
1759
497k
  // trunc or zext to the intptr_t type, then inttoptr of it.  This allows the
1760
497k
  // cast to be exposed to other transforms.
1761
497k
  unsigned AS = CI.getAddressSpace();
1762
497k
  if (CI.getOperand(0)->getType()->getScalarSizeInBits() !=
1763
497k
      DL.getPointerSizeInBits(AS)) {
1764
38
    Type *Ty = DL.getIntPtrType(CI.getContext(), AS);
1765
38
    if (CI.getType()->isVectorTy()) // Handle vectors of pointers.
1766
2
      Ty = VectorType::get(Ty, CI.getType()->getVectorNumElements());
1767
38
1768
38
    Value *P = Builder.CreateZExtOrTrunc(CI.getOperand(0), Ty);
1769
38
    return new IntToPtrInst(P, CI.getType());
1770
38
  }
1771
497k
1772
497k
  if (Instruction *I = commonCastTransforms(CI))
1773
2.74k
    return I;
1774
494k
1775
494k
  return nullptr;
1776
494k
}
1777
1778
/// Implement the transforms for cast of pointer (bitcast/ptrtoint)
1779
8.82M
Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
1780
8.82M
  Value *Src = CI.getOperand(0);
1781
8.82M
1782
8.82M
  if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
1783
4.51M
    // If casting the result of a getelementptr instruction with no offset, turn
1784
4.51M
    // this into a cast of the original pointer!
1785
4.51M
    if (GEP->hasAllZeroIndices() &&
1786
4.51M
        // If CI is an addrspacecast and GEP changes the poiner type, merging
1787
4.51M
        // GEP into CI would undo canonicalizing addrspacecast with different
1788
4.51M
        // pointer types, causing infinite loops.
1789
4.51M
        
(47.6k
!isa<AddrSpaceCastInst>(CI)47.6k
||
1790
47.6k
         
GEP->getType() == GEP->getPointerOperandType()15
)) {
1791
47.6k
      // Changing the cast operand is usually not a good idea but it is safe
1792
47.6k
      // here because the pointer operand is being replaced with another
1793
47.6k
      // pointer operand so the opcode doesn't need to change.
1794
47.6k
      Worklist.Add(GEP);
1795
47.6k
      CI.setOperand(0, GEP->getOperand(0));
1796
47.6k
      return &CI;
1797
47.6k
    }
1798
8.77M
  }
1799
8.77M
1800
8.77M
  return commonCastTransforms(CI);
1801
8.77M
}
1802
1803
1.15M
Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
1804
1.15M
  // If the destination integer type is not the intptr_t type for this target,
1805
1.15M
  // do a ptrtoint to intptr_t then do a trunc or zext.  This allows the cast
1806
1.15M
  // to be exposed to other transforms.
1807
1.15M
1808
1.15M
  Type *Ty = CI.getType();
1809
1.15M
  unsigned AS = CI.getPointerAddressSpace();
1810
1.15M
1811
1.15M
  if (Ty->getScalarSizeInBits() == DL.getIndexSizeInBits(AS))
1812
1.15M
    return commonPointerCastTransforms(CI);
1813
745
1814
745
  Type *PtrTy = DL.getIntPtrType(CI.getContext(), AS);
1815
745
  if (Ty->isVectorTy()) // Handle vectors of pointers.
1816
2
    PtrTy = VectorType::get(PtrTy, Ty->getVectorNumElements());
1817
745
1818
745
  Value *P = Builder.CreatePtrToInt(CI.getOperand(0), PtrTy);
1819
745
  return CastInst::CreateIntegerCast(P, Ty, /*isSigned=*/false);
1820
745
}
1821
1822
/// This input value (which is known to have vector type) is being zero extended
1823
/// or truncated to the specified vector type.
1824
/// Try to replace it with a shuffle (and vector/vector bitcast) if possible.
1825
///
1826
/// The source and destination vector types may have different element types.
1827
static Instruction *optimizeVectorResize(Value *InVal, VectorType *DestTy,
1828
3
                                         InstCombiner &IC) {
1829
3
  // We can only do this optimization if the output is a multiple of the input
1830
3
  // element size, or the input is a multiple of the output element size.
1831
3
  // Convert the input type to have the same element type as the output.
1832
3
  VectorType *SrcTy = cast<VectorType>(InVal->getType());
1833
3
1834
3
  if (SrcTy->getElementType() != DestTy->getElementType()) {
1835
1
    // The input types don't need to be identical, but for now they must be the
1836
1
    // same size.  There is no specific reason we couldn't handle things like
1837
1
    // <4 x i16> -> <4 x i32> by bitcasting to <2 x i32> but haven't gotten
1838
1
    // there yet.
1839
1
    if (SrcTy->getElementType()->getPrimitiveSizeInBits() !=
1840
1
        DestTy->getElementType()->getPrimitiveSizeInBits())
1841
0
      return nullptr;
1842
1
1843
1
    SrcTy = VectorType::get(DestTy->getElementType(), SrcTy->getNumElements());
1844
1
    InVal = IC.Builder.CreateBitCast(InVal, SrcTy);
1845
1
  }
1846
3
1847
3
  // Now that the element types match, get the shuffle mask and RHS of the
1848
3
  // shuffle to use, which depends on whether we're increasing or decreasing the
1849
3
  // size of the input.
1850
3
  SmallVector<uint32_t, 16> ShuffleMask;
1851
3
  Value *V2;
1852
3
1853
3
  if (SrcTy->getNumElements() > DestTy->getNumElements()) {
1854
1
    // If we're shrinking the number of elements, just shuffle in the low
1855
1
    // elements from the input and use undef as the second shuffle input.
1856
1
    V2 = UndefValue::get(SrcTy);
1857
4
    for (unsigned i = 0, e = DestTy->getNumElements(); i != e; 
++i3
)
1858
3
      ShuffleMask.push_back(i);
1859
1
1860
2
  } else {
1861
2
    // If we're increasing the number of elements, shuffle in all of the
1862
2
    // elements from InVal and fill the rest of the result elements with zeros
1863
2
    // from a constant zero.
1864
2
    V2 = Constant::getNullValue(SrcTy);
1865
2
    unsigned SrcElts = SrcTy->getNumElements();
1866
8
    for (unsigned i = 0, e = SrcElts; i != e; 
++i6
)
1867
6
      ShuffleMask.push_back(i);
1868
2
1869
2
    // The excess elements reference the first element of the zero input.
1870
4
    for (unsigned i = 0, e = DestTy->getNumElements()-SrcElts; i != e; 
++i2
)
1871
2
      ShuffleMask.push_back(SrcElts);
1872
2
  }
1873
3
1874
3
  return new ShuffleVectorInst(InVal, V2,
1875
3
                               ConstantDataVector::get(V2->getContext(),
1876
3
                                                       ShuffleMask));
1877
3
}
1878
1879
16
static bool isMultipleOfTypeSize(unsigned Value, Type *Ty) {
1880
16
  return Value % Ty->getPrimitiveSizeInBits() == 0;
1881
16
}
1882
1883
18
static unsigned getTypeSizeIndex(unsigned Value, Type *Ty) {
1884
18
  return Value / Ty->getPrimitiveSizeInBits();
1885
18
}
1886
1887
/// V is a value which is inserted into a vector of VecEltTy.
1888
/// Look through the value to see if we can decompose it into
1889
/// insertions into the vector.  See the example in the comment for
1890
/// OptimizeIntegerToVectorInsertions for the pattern this handles.
1891
/// The type of V is always a non-zero multiple of VecEltTy's size.
1892
/// Shift is the number of bits between the lsb of V and the lsb of
1893
/// the vector.
1894
///
1895
/// This returns false if the pattern can't be matched or true if it can,
1896
/// filling in Elements with the elements found here.
1897
static bool collectInsertionElements(Value *V, unsigned Shift,
1898
                                     SmallVectorImpl<Value *> &Elements,
1899
582
                                     Type *VecEltTy, bool isBigEndian) {
1900
582
  assert(isMultipleOfTypeSize(Shift, VecEltTy) &&
1901
582
         "Shift should be a multiple of the element type size");
1902
582
1903
582
  // Undef values never contribute useful bits to the result.
1904
582
  if (isa<UndefValue>(V)) 
return true0
;
1905
582
1906
582
  // If we got down to a value of the right type, we win, try inserting into the
1907
582
  // right element.
1908
582
  if (V->getType() == VecEltTy) {
1909
14
    // Inserting null doesn't actually insert any elements.
1910
14
    if (Constant *C = dyn_cast<Constant>(V))
1911
4
      if (C->isNullValue())
1912
2
        return true;
1913
12
1914
12
    unsigned ElementIndex = getTypeSizeIndex(Shift, VecEltTy);
1915
12
    if (isBigEndian)
1916
6
      ElementIndex = Elements.size() - ElementIndex - 1;
1917
12
1918
12
    // Fail if multiple elements are inserted into this slot.
1919
12
    if (Elements[ElementIndex])
1920
0
      return false;
1921
12
1922
12
    Elements[ElementIndex] = V;
1923
12
    return true;
1924
12
  }
1925
568
1926
568
  if (Constant *C = dyn_cast<Constant>(V)) {
1927
6
    // Figure out the # elements this provides, and bitcast it or slice it up
1928
6
    // as required.
1929
6
    unsigned NumElts = getTypeSizeIndex(C->getType()->getPrimitiveSizeInBits(),
1930
6
                                        VecEltTy);
1931
6
    // If the constant is the size of a vector element, we just need to bitcast
1932
6
    // it to the right type so it gets properly inserted.
1933
6
    if (NumElts == 1)
1934
4
      return collectInsertionElements(ConstantExpr::getBitCast(C, VecEltTy),
1935
4
                                      Shift, Elements, VecEltTy, isBigEndian);
1936
2
1937
2
    // Okay, this is a constant that covers multiple elements.  Slice it up into
1938
2
    // pieces and insert each element-sized piece into the vector.
1939
2
    if (!isa<IntegerType>(C->getType()))
1940
0
      C = ConstantExpr::getBitCast(C, IntegerType::get(V->getContext(),
1941
0
                                       C->getType()->getPrimitiveSizeInBits()));
1942
2
    unsigned ElementSize = VecEltTy->getPrimitiveSizeInBits();
1943
2
    Type *ElementIntTy = IntegerType::get(C->getContext(), ElementSize);
1944
2
1945
6
    for (unsigned i = 0; i != NumElts; 
++i4
) {
1946
4
      unsigned ShiftI = Shift+i*ElementSize;
1947
4
      Constant *Piece = ConstantExpr::getLShr(C, ConstantInt::get(C->getType(),
1948
4
                                                                  ShiftI));
1949
4
      Piece = ConstantExpr::getTrunc(Piece, ElementIntTy);
1950
4
      if (!collectInsertionElements(Piece, ShiftI, Elements, VecEltTy,
1951
4
                                    isBigEndian))
1952
0
        return false;
1953
4
    }
1954
2
    return true;
1955
562
  }
1956
562
1957
562
  if (!V->hasOneUse()) 
return false6
;
1958
556
1959
556
  Instruction *I = dyn_cast<Instruction>(V);
1960
556
  if (!I) 
return false351
;
1961
205
  switch (I->getOpcode()) {
1962
205
  
default: return false176
; // Unhandled case.
1963
205
  case Instruction::BitCast:
1964
7
    return collectInsertionElements(I->getOperand(0), Shift, Elements, VecEltTy,
1965
7
                                    isBigEndian);
1966
205
  case Instruction::ZExt:
1967
10
    if (!isMultipleOfTypeSize(
1968
10
                          I->getOperand(0)->getType()->getPrimitiveSizeInBits(),
1969
10
                              VecEltTy))
1970
0
      return false;
1971
10
    return collectInsertionElements(I->getOperand(0), Shift, Elements, VecEltTy,
1972
10
                                    isBigEndian);
1973
10
  case Instruction::Or:
1974
6
    return collectInsertionElements(I->getOperand(0), Shift, Elements, VecEltTy,
1975
6
                                    isBigEndian) &&
1976
6
           collectInsertionElements(I->getOperand(1), Shift, Elements, VecEltTy,
1977
6
                                    isBigEndian);
1978
10
  case Instruction::Shl: {
1979
6
    // Must be shifting by a constant that is a multiple of the element size.
1980
6
    ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1));
1981
6
    if (!CI) 
return false0
;
1982
6
    Shift += CI->getZExtValue();
1983
6
    if (!isMultipleOfTypeSize(Shift, VecEltTy)) 
return false0
;
1984
6
    return collectInsertionElements(I->getOperand(0), Shift, Elements, VecEltTy,
1985
6
                                    isBigEndian);
1986
6
  }
1987
205
1988
205
  }
1989
205
}
1990
1991
1992
/// If the input is an 'or' instruction, we may be doing shifts and ors to
1993
/// assemble the elements of the vector manually.
1994
/// Try to rip the code out and replace it with insertelements.  This is to
1995
/// optimize code like this:
1996
///
1997
///    %tmp37 = bitcast float %inc to i32
1998
///    %tmp38 = zext i32 %tmp37 to i64
1999
///    %tmp31 = bitcast float %inc5 to i32
2000
///    %tmp32 = zext i32 %tmp31 to i64
2001
///    %tmp33 = shl i64 %tmp32, 32
2002
///    %ins35 = or i64 %tmp33, %tmp38
2003
///    %tmp43 = bitcast i64 %ins35 to <2 x float>
2004
///
2005
/// Into two insertelements that do "buildvector{%inc, %inc5}".
2006
static Value *optimizeIntegerToVectorInsertions(BitCastInst &CI,
2007
539
                                                InstCombiner &IC) {
2008
539
  VectorType *DestVecTy = cast<VectorType>(CI.getType());
2009
539
  Value *IntInput = CI.getOperand(0);
2010
539
2011
539
  SmallVector<Value*, 8> Elements(DestVecTy->getNumElements());
2012
539
  if (!collectInsertionElements(IntInput, 0, Elements,
2013
539
                                DestVecTy->getElementType(),
2014
539
                                IC.getDataLayout().isBigEndian()))
2015
533
    return nullptr;
2016
6
2017
6
  // If we succeeded, we know that all of the element are specified by Elements
2018
6
  // or are zero if Elements has a null entry.  Recast this as a set of
2019
6
  // insertions.
2020
6
  Value *Result = Constant::getNullValue(CI.getType());
2021
18
  for (unsigned i = 0, e = Elements.size(); i != e; 
++i12
) {
2022
12
    if (!Elements[i]) 
continue0
; // Unset element.
2023
12
2024
12
    Result = IC.Builder.CreateInsertElement(Result, Elements[i],
2025
12
                                            IC.Builder.getInt32(i));
2026
12
  }
2027
6
2028
6
  return Result;
2029
6
}
2030
2031
/// Canonicalize scalar bitcasts of extracted elements into a bitcast of the
2032
/// vector followed by extract element. The backend tends to handle bitcasts of
2033
/// vectors better than bitcasts of scalars because vector registers are
2034
/// usually not type-specific like scalar integer or scalar floating-point.
2035
static Instruction *canonicalizeBitCastExtElt(BitCastInst &BitCast,
2036
7.79M
                                              InstCombiner &IC) {
2037
7.79M
  // TODO: Create and use a pattern matcher for ExtractElementInst.
2038
7.79M
  auto *ExtElt = dyn_cast<ExtractElementInst>(BitCast.getOperand(0));
2039
7.79M
  if (!ExtElt || 
!ExtElt->hasOneUse()299
)
2040
7.79M
    return nullptr;
2041
290
2042
290
  // The bitcast must be to a vectorizable type, otherwise we can't make a new
2043
290
  // type to extract from.
2044
290
  Type *DestType = BitCast.getType();
2045
290
  if (!VectorType::isValidElementType(DestType))
2046
170
    return nullptr;
2047
120
2048
120
  unsigned NumElts = ExtElt->getVectorOperandType()->getNumElements();
2049
120
  auto *NewVecType = VectorType::get(DestType, NumElts);
2050
120
  auto *NewBC = IC.Builder.CreateBitCast(ExtElt->getVectorOperand(),
2051
120
                                         NewVecType, "bc");
2052
120
  return ExtractElementInst::Create(NewBC, ExtElt->getIndexOperand());
2053
120
}
2054
2055
/// Change the type of a bitwise logic operation if we can eliminate a bitcast.
2056
static Instruction *foldBitCastBitwiseLogic(BitCastInst &BitCast,
2057
7.79M
                                            InstCombiner::BuilderTy &Builder) {
2058
7.79M
  Type *DestTy = BitCast.getType();
2059
7.79M
  BinaryOperator *BO;
2060
7.79M
  if (!DestTy->isIntOrIntVectorTy() ||
2061
7.79M
      
!match(BitCast.getOperand(0), m_OneUse(m_BinOp(BO)))61.3k
||
2062
7.79M
      
!BO->isBitwiseLogicOp()2.15k
)
2063
7.79M
    return nullptr;
2064
35
2065
35
  // FIXME: This transform is restricted to vector types to avoid backend
2066
35
  // problems caused by creating potentially illegal operations. If a fix-up is
2067
35
  // added to handle that situation, we can remove this check.
2068
35
  if (!DestTy->isVectorTy() || 
!BO->getType()->isVectorTy()32
)
2069
5
    return nullptr;
2070
30
2071
30
  Value *X;
2072
30
  if (match(BO->getOperand(0), m_OneUse(m_BitCast(m_Value(X)))) &&
2073
30
      
X->getType() == DestTy7
&&
!isa<Constant>(X)0
) {
2074
0
    // bitcast(logic(bitcast(X), Y)) --> logic'(X, bitcast(Y))
2075
0
    Value *CastedOp1 = Builder.CreateBitCast(BO->getOperand(1), DestTy);
2076
0
    return BinaryOperator::Create(BO->getOpcode(), X, CastedOp1);
2077
0
  }
2078
30
2079
30
  if (match(BO->getOperand(1), m_OneUse(m_BitCast(m_Value(X)))) &&
2080
30
      
X->getType() == DestTy1
&&
!isa<Constant>(X)1
) {
2081
1
    // bitcast(logic(Y, bitcast(X))) --> logic'(bitcast(Y), X)
2082
1
    Value *CastedOp0 = Builder.CreateBitCast(BO->getOperand(0), DestTy);
2083
1
    return BinaryOperator::Create(BO->getOpcode(), CastedOp0, X);
2084
1
  }
2085
29
2086
29
  // Canonicalize vector bitcasts to come before vector bitwise logic with a
2087
29
  // constant. This eases recognition of special constants for later ops.
2088
29
  // Example:
2089
29
  // icmp u/s (a ^ signmask), (b ^ signmask) --> icmp s/u a, b
2090
29
  Constant *C;
2091
29
  if (match(BO->getOperand(1), m_Constant(C))) {
2092
21
    // bitcast (logic X, C) --> logic (bitcast X, C')
2093
21
    Value *CastedOp0 = Builder.CreateBitCast(BO->getOperand(0), DestTy);
2094
21
    Value *CastedC = ConstantExpr::getBitCast(C, DestTy);
2095
21
    return BinaryOperator::Create(BO->getOpcode(), CastedOp0, CastedC);
2096
21
  }
2097
8
2098
8
  return nullptr;
2099
8
}
2100
2101
/// Change the type of a select if we can eliminate a bitcast.
2102
static Instruction *foldBitCastSelect(BitCastInst &BitCast,
2103
7.79M
                                      InstCombiner::BuilderTy &Builder) {
2104
7.79M
  Value *Cond, *TVal, *FVal;
2105
7.79M
  if (!match(BitCast.getOperand(0),
2106
7.79M
             m_OneUse(m_Select(m_Value(Cond), m_Value(TVal), m_Value(FVal)))))
2107
7.79M
    return nullptr;
2108
1.89k
2109
1.89k
  // A vector select must maintain the same number of elements in its operands.
2110
1.89k
  Type *CondTy = Cond->getType();
2111
1.89k
  Type *DestTy = BitCast.getType();
2112
1.89k
  if (CondTy->isVectorTy()) {
2113
50
    if (!DestTy->isVectorTy())
2114
7
      return nullptr;
2115
43
    if (DestTy->getVectorNumElements() != CondTy->getVectorNumElements())
2116
24
      return nullptr;
2117
1.86k
  }
2118
1.86k
2119
1.86k
  // FIXME: This transform is restricted from changing the select between
2120
1.86k
  // scalars and vectors to avoid backend problems caused by creating
2121
1.86k
  // potentially illegal operations. If a fix-up is added to handle that
2122
1.86k
  // situation, we can remove this check.
2123
1.86k
  if (DestTy->isVectorTy() != TVal->getType()->isVectorTy())
2124
2
    return nullptr;
2125
1.86k
2126
1.86k
  auto *Sel = cast<Instruction>(BitCast.getOperand(0));
2127
1.86k
  Value *X;
2128
1.86k
  if (match(TVal, m_OneUse(m_BitCast(m_Value(X)))) && 
X->getType() == DestTy9
&&
2129
1.86k
      
!isa<Constant>(X)9
) {
2130
9
    // bitcast(select(Cond, bitcast(X), Y)) --> select'(Cond, X, bitcast(Y))
2131
9
    Value *CastedVal = Builder.CreateBitCast(FVal, DestTy);
2132
9
    return SelectInst::Create(Cond, X, CastedVal, "", nullptr, Sel);
2133
9
  }
2134
1.85k
2135
1.85k
  if (match(FVal, m_OneUse(m_BitCast(m_Value(X)))) && 
X->getType() == DestTy23
&&
2136
1.85k
      
!isa<Constant>(X)23
) {
2137
23
    // bitcast(select(Cond, Y, bitcast(X))) --> select'(Cond, bitcast(Y), X)
2138
23
    Value *CastedVal = Builder.CreateBitCast(TVal, DestTy);
2139
23
    return SelectInst::Create(Cond, CastedVal, X, "", nullptr, Sel);
2140
23
  }
2141
1.83k
2142
1.83k
  return nullptr;
2143
1.83k
}
2144
2145
/// Check if all users of CI are StoreInsts.
2146
312k
static bool hasStoreUsersOnly(CastInst &CI) {
2147
318k
  for (User *U : CI.users()) {
2148
318k
    if (!isa<StoreInst>(U))
2149
243k
      return false;
2150
318k
  }
2151
312k
  
return true69.1k
;
2152
312k
}
2153
2154
/// This function handles following case
2155
///
2156
///     A  ->  B    cast
2157
///     PHI
2158
///     B  ->  A    cast
2159
///
2160
/// All the related PHI nodes can be replaced by new PHI nodes with type A.
2161
/// The uses of \p CI can be changed to the new PHI node corresponding to \p PN.
2162
312k
Instruction *InstCombiner::optimizeBitCastFromPhi(CastInst &CI, PHINode *PN) {
2163
312k
  // BitCast used by Store can be handled in InstCombineLoadStoreAlloca.cpp.
2164
312k
  if (hasStoreUsersOnly(CI))
2165
69.1k
    return nullptr;
2166
243k
2167
243k
  Value *Src = CI.getOperand(0);
2168
243k
  Type *SrcTy = Src->getType();         // Type B
2169
243k
  Type *DestTy = CI.getType();          // Type A
2170
243k
2171
243k
  SmallVector<PHINode *, 4> PhiWorklist;
2172
243k
  SmallSetVector<PHINode *, 4> OldPhiNodes;
2173
243k
2174
243k
  // Find all of the A->B casts and PHI nodes.
2175
243k
  // We need to inspect all related PHI nodes, but PHIs can be cyclic, so
2176
243k
  // OldPhiNodes is used to track all known PHI nodes, before adding a new
2177
243k
  // PHI to PhiWorklist, it is checked against and added to OldPhiNodes first.
2178
243k
  PhiWorklist.push_back(PN);
2179
243k
  OldPhiNodes.insert(PN);
2180
255k
  while (!PhiWorklist.empty()) {
2181
253k
    auto *OldPN = PhiWorklist.pop_back_val();
2182
321k
    for (Value *IncValue : OldPN->incoming_values()) {
2183
321k
      if (isa<Constant>(IncValue))
2184
4.88k
        continue;
2185
316k
2186
316k
      if (auto *LI = dyn_cast<LoadInst>(IncValue)) {
2187
164k
        // If there is a sequence of one or more load instructions, each loaded
2188
164k
        // value is used as address of later load instruction, bitcast is
2189
164k
        // necessary to change the value type, don't optimize it. For
2190
164k
        // simplicity we give up if the load address comes from another load.
2191
164k
        Value *Addr = LI->getOperand(0);
2192
164k
        if (Addr == &CI || 
isa<LoadInst>(Addr)152k
)
2193
11.5k
          return nullptr;
2194
152k
        if (LI->hasOneUse() && 
LI->isSimple()28.9k
)
2195
28.9k
          continue;
2196
123k
        // If a LoadInst has more than one use, changing the type of loaded
2197
123k
        // value may create another bitcast.
2198
123k
        return nullptr;
2199
123k
      }
2200
152k
2201
152k
      if (auto *PNode = dyn_cast<PHINode>(IncValue)) {
2202
43.2k
        if (OldPhiNodes.insert(PNode))
2203
30.3k
          PhiWorklist.push_back(PNode);
2204
43.2k
        continue;
2205
43.2k
      }
2206
109k
2207
109k
      auto *BCI = dyn_cast<BitCastInst>(IncValue);
2208
109k
      // We can't handle other instructions.
2209
109k
      if (!BCI)
2210
103k
        return nullptr;
2211
6.31k
2212
6.31k
      // Verify it's a A->B cast.
2213
6.31k
      Type *TyA = BCI->getOperand(0)->getType();
2214
6.31k
      Type *TyB = BCI->getType();
2215
6.31k
      if (TyA != DestTy || 
TyB != SrcTy3.00k
)
2216
3.30k
        return nullptr;
2217
6.31k
    }
2218
253k
  }
2219
243k
2220
243k
  // For each old PHI node, create a corresponding new PHI node with a type A.
2221
243k
  SmallDenseMap<PHINode *, PHINode *> NewPNodes;
2222
2.81k
  for (auto *OldPN : OldPhiNodes) {
2223
2.81k
    Builder.SetInsertPoint(OldPN);
2224
2.81k
    PHINode *NewPN = Builder.CreatePHI(DestTy, OldPN->getNumOperands());
2225
2.81k
    NewPNodes[OldPN] = NewPN;
2226
2.81k
  }
2227
1.90k
2228
1.90k
  // Fill in the operands of new PHI nodes.
2229
2.81k
  for (auto *OldPN : OldPhiNodes) {
2230
2.81k
    PHINode *NewPN = NewPNodes[OldPN];
2231
9.70k
    for (unsigned j = 0, e = OldPN->getNumOperands(); j != e; 
++j6.88k
) {
2232
6.88k
      Value *V = OldPN->getOperand(j);
2233
6.88k
      Value *NewV = nullptr;
2234
6.88k
      if (auto *C = dyn_cast<Constant>(V)) {
2235
1.46k
        NewV = ConstantExpr::getBitCast(C, DestTy);
2236
5.42k
      } else if (auto *LI = dyn_cast<LoadInst>(V)) {
2237
1.19k
        Builder.SetInsertPoint(LI->getNextNode());
2238
1.19k
        NewV = Builder.CreateBitCast(LI, DestTy);
2239
1.19k
        Worklist.Add(LI);
2240
4.22k
      } else if (auto *BCI = dyn_cast<BitCastInst>(V)) {
2241
2.08k
        NewV = BCI->getOperand(0);
2242
2.14k
      } else if (auto *PrevPN = dyn_cast<PHINode>(V)) {
2243
2.14k
        NewV = NewPNodes[PrevPN];
2244
2.14k
      }
2245
6.88k
      assert(NewV);
2246
6.88k
      NewPN->addIncoming(NewV, OldPN->getIncomingBlock(j));
2247
6.88k
    }
2248
2.81k
  }
2249
1.90k
2250
1.90k
  // Traverse all accumulated PHI nodes and process its users,
2251
1.90k
  // which are Stores and BitcCasts. Without this processing
2252
1.90k
  // NewPHI nodes could be replicated and could lead to extra
2253
1.90k
  // moves generated after DeSSA.
2254
1.90k
  // If there is a store with type B, change it to type A.
2255
1.90k
2256
1.90k
2257
1.90k
  // Replace users of BitCast B->A with NewPHI. These will help
2258
1.90k
  // later to get rid off a closure formed by OldPHI nodes.
2259
1.90k
  Instruction *RetVal = nullptr;
2260
2.81k
  for (auto *OldPN : OldPhiNodes) {
2261
2.81k
    PHINode *NewPN = NewPNodes[OldPN];
2262
9.58k
    for (User *V : OldPN->users()) {
2263
9.58k
      if (auto *SI = dyn_cast<StoreInst>(V)) {
2264
213
        if (SI->isSimple() && SI->getOperand(0) == OldPN) {
2265
185
          Builder.SetInsertPoint(SI);
2266
185
          auto *NewBC =
2267
185
            cast<BitCastInst>(Builder.CreateBitCast(NewPN, SrcTy));
2268
185
          SI->setOperand(0, NewBC);
2269
185
          Worklist.Add(SI);
2270
185
          assert(hasStoreUsersOnly(*NewBC));
2271
185
        }
2272
213
      }
2273
9.37k
      else if (auto *BCI = dyn_cast<BitCastInst>(V)) {
2274
2.36k
        // Verify it's a B->A cast.
2275
2.36k
        Type *TyB = BCI->getOperand(0)->getType();
2276
2.36k
        Type *TyA = BCI->getType();
2277
2.36k
        if (TyA == DestTy && 
TyB == SrcTy2.31k
) {
2278
2.31k
          Instruction *I = replaceInstUsesWith(*BCI, NewPN);
2279
2.31k
          if (BCI == &CI)
2280
1.80k
            RetVal = I;
2281
2.31k
        }
2282
2.36k
      }
2283
9.58k
    }
2284
2.81k
  }
2285
1.90k
2286
1.90k
  return RetVal;
2287
243k
}
2288
2289
7.99M
Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
2290
7.99M
  // If the operands are integer typed then apply the integer transforms,
2291
7.99M
  // otherwise just apply the common ones.
2292
7.99M
  Value *Src = CI.getOperand(0);
2293
7.99M
  Type *SrcTy = Src->getType();
2294
7.99M
  Type *DestTy = CI.getType();
2295
7.99M
2296
7.99M
  // Get rid of casts from one type to the same type. These are useless and can
2297
7.99M
  // be replaced by the operand.
2298
7.99M
  if (DestTy == Src->getType())
2299
30.8k
    return replaceInstUsesWith(CI, Src);
2300
7.96M
2301
7.96M
  if (PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
2302
7.83M
    PointerType *SrcPTy = cast<PointerType>(SrcTy);
2303
7.83M
    Type *DstElTy = DstPTy->getElementType();
2304
7.83M
    Type *SrcElTy = SrcPTy->getElementType();
2305
7.83M
2306
7.83M
    // Casting pointers between the same type, but with different address spaces
2307
7.83M
    // is an addrspace cast rather than a bitcast.
2308
7.83M
    if ((DstElTy == SrcElTy) &&
2309
7.83M
        
(DstPTy->getAddressSpace() != SrcPTy->getAddressSpace())0
)
2310
0
      return new AddrSpaceCastInst(Src, DestTy);
2311
7.83M
2312
7.83M
    // If we are casting a alloca to a pointer to a type of the same
2313
7.83M
    // size, rewrite the allocation instruction to allocate the "right" type.
2314
7.83M
    // There is no need to modify malloc calls because it is their bitcast that
2315
7.83M
    // needs to be cleaned up.
2316
7.83M
    if (AllocaInst *AI = dyn_cast<AllocaInst>(Src))
2317
1.04M
      if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
2318
1.07k
        return V;
2319
7.83M
2320
7.83M
    // When the type pointed to is not sized the cast cannot be
2321
7.83M
    // turned into a gep.
2322
7.83M
    Type *PointeeType =
2323
7.83M
        cast<PointerType>(Src->getType()->getScalarType())->getElementType();
2324
7.83M
    if (!PointeeType->isSized())
2325
33.0k
      return nullptr;
2326
7.80M
2327
7.80M
    // If the source and destination are pointers, and this cast is equivalent
2328
7.80M
    // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
2329
7.80M
    // This can enhance SROA and other transforms that want type-safe pointers.
2330
7.80M
    unsigned NumZeros = 0;
2331
13.9M
    while (SrcElTy != DstElTy &&
2332
13.9M
           
isa<CompositeType>(SrcElTy)13.7M
&&
!SrcElTy->isPointerTy()6.11M
&&
2333
13.9M
           
SrcElTy->getNumContainedTypes()6.11M
/* not "{}" */) {
2334
6.11M
      SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(0U);
2335
6.11M
      ++NumZeros;
2336
6.11M
    }
2337
7.80M
2338
7.80M
    // If we found a path from the src to dest, create the getelementptr now.
2339
7.80M
    if (SrcElTy == DstElTy) {
2340
133k
      SmallVector<Value *, 8> Idxs(NumZeros + 1, Builder.getInt32(0));
2341
133k
      return GetElementPtrInst::CreateInBounds(SrcPTy->getElementType(), Src,
2342
133k
                                               Idxs);
2343
133k
    }
2344
7.79M
  }
2345
7.79M
2346
7.79M
  if (VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
2347
45.5k
    if (DestVTy->getNumElements() == 1 && 
!SrcTy->isVectorTy()6.43k
) {
2348
20
      Value *Elem = Builder.CreateBitCast(Src, DestVTy->getElementType());
2349
20
      return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
2350
20
                     Constant::getNullValue(Type::getInt32Ty(CI.getContext())));
2351
20
      // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
2352
20
    }
2353
45.5k
2354
45.5k
    if (isa<IntegerType>(SrcTy)) {
2355
542
      // If this is a cast from an integer to vector, check to see if the input
2356
542
      // is a trunc or zext of a bitcast from vector.  If so, we can replace all
2357
542
      // the casts with a shuffle and (potentially) a bitcast.
2358
542
      if (isa<TruncInst>(Src) || 
isa<ZExtInst>(Src)541
) {
2359
3
        CastInst *SrcCast = cast<CastInst>(Src);
2360
3
        if (BitCastInst *BCIn = dyn_cast<BitCastInst>(SrcCast->getOperand(0)))
2361
3
          if (isa<VectorType>(BCIn->getOperand(0)->getType()))
2362
3
            if (Instruction *I = optimizeVectorResize(BCIn->getOperand(0),
2363
3
                                               cast<VectorType>(DestTy), *this))
2364
3
              return I;
2365
539
      }
2366
539
2367
539
      // If the input is an 'or' instruction, we may be doing shifts and ors to
2368
539
      // assemble the elements of the vector manually.  Try to rip the code out
2369
539
      // and replace it with insertelements.
2370
539
      if (Value *V = optimizeIntegerToVectorInsertions(CI, *this))
2371
6
        return replaceInstUsesWith(CI, V);
2372
7.79M
    }
2373
45.5k
  }
2374
7.79M
2375
7.79M
  if (VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
2376
46.5k
    if (SrcVTy->getNumElements() == 1) {
2377
154
      // If our destination is not a vector, then make this a straight
2378
154
      // scalar-scalar cast.
2379
154
      if (!DestTy->isVectorTy()) {
2380
22
        Value *Elem =
2381
22
          Builder.CreateExtractElement(Src,
2382
22
                     Constant::getNullValue(Type::getInt32Ty(CI.getContext())));
2383
22
        return CastInst::Create(Instruction::BitCast, Elem, DestTy);
2384
22
      }
2385
132
2386
132
      // Otherwise, see if our source is an insert. If so, then use the scalar
2387
132
      // component directly:
2388
132
      // bitcast (inselt <1 x elt> V, X, 0) to <n x m> --> bitcast X to <n x m>
2389
132
      if (auto *InsElt = dyn_cast<InsertElementInst>(Src))
2390
6
        return new BitCastInst(InsElt->getOperand(1), DestTy);
2391
7.79M
    }
2392
46.5k
  }
2393
7.79M
2394
7.79M
  if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
2395
6.12k
    // Okay, we have (bitcast (shuffle ..)).  Check to see if this is
2396
6.12k
    // a bitcast to a vector with the same # elts.
2397
6.12k
    if (SVI->hasOneUse() && DestTy->isVectorTy() &&
2398
6.12k
        
DestTy->getVectorNumElements() == SVI->getType()->getNumElements()6.07k
&&
2399
6.12k
        SVI->getType()->getNumElements() ==
2400
4.91k
        SVI->getOperand(0)->getType()->getVectorNumElements()) {
2401
4.90k
      BitCastInst *Tmp;
2402
4.90k
      // If either of the operands is a cast from CI.getType(), then
2403
4.90k
      // evaluating the shuffle in the casted destination's type will allow
2404
4.90k
      // us to eliminate at least one cast.
2405
4.90k
      if (((Tmp = dyn_cast<BitCastInst>(SVI->getOperand(0))) &&
2406
4.90k
           
Tmp->getOperand(0)->getType() == DestTy2.48k
) ||
2407
4.90k
          
(4.90k
(Tmp = dyn_cast<BitCastInst>(SVI->getOperand(1)))4.90k
&&
2408
4.90k
           
Tmp->getOperand(0)->getType() == DestTy0
)) {
2409
1
        Value *LHS = Builder.CreateBitCast(SVI->getOperand(0), DestTy);
2410
1
        Value *RHS = Builder.CreateBitCast(SVI->getOperand(1), DestTy);
2411
1
        // Return a new shuffle vector.  Use the same element ID's, as we
2412
1
        // know the vector types match #elts.
2413
1
        return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
2414
1
      }
2415
7.79M
    }
2416
6.12k
  }
2417
7.79M
2418
7.79M
  // Handle the A->B->A cast, and there is an intervening PHI node.
2419
7.79M
  if (PHINode *PN = dyn_cast<PHINode>(Src))
2420
312k
    if (Instruction *I = optimizeBitCastFromPhi(CI, PN))
2421
1.80k
      return I;
2422
7.79M
2423
7.79M
  if (Instruction *I = canonicalizeBitCastExtElt(CI, *this))
2424
119
    return I;
2425
7.79M
2426
7.79M
  if (Instruction *I = foldBitCastBitwiseLogic(CI, Builder))
2427
22
    return I;
2428
7.79M
2429
7.79M
  if (Instruction *I = foldBitCastSelect(CI, Builder))
2430
32
    return I;
2431
7.79M
2432
7.79M
  if (SrcTy->isPointerTy())
2433
7.66M
    return commonPointerCastTransforms(CI);
2434
129k
  return commonCastTransforms(CI);
2435
129k
}
2436
2437
856
Instruction *InstCombiner::visitAddrSpaceCast(AddrSpaceCastInst &CI) {
2438
856
  // If the destination pointer element type is not the same as the source's
2439
856
  // first do a bitcast to the destination type, and then the addrspacecast.
2440
856
  // This allows the cast to be exposed to other transforms.
2441
856
  Value *Src = CI.getOperand(0);
2442
856
  PointerType *SrcTy = cast<PointerType>(Src->getType()->getScalarType());
2443
856
  PointerType *DestTy = cast<PointerType>(CI.getType()->getScalarType());
2444
856
2445
856
  Type *DestElemTy = DestTy->getElementType();
2446
856
  if (SrcTy->getElementType() != DestElemTy) {
2447
81
    Type *MidTy = PointerType::get(DestElemTy, SrcTy->getAddressSpace());
2448
81
    if (VectorType *VT = dyn_cast<VectorType>(CI.getType())) {
2449
3
      // Handle vectors of pointers.
2450
3
      MidTy = VectorType::get(MidTy, VT->getNumElements());
2451
3
    }
2452
81
2453
81
    Value *NewBitCast = Builder.CreateBitCast(Src, MidTy);
2454
81
    return new AddrSpaceCastInst(NewBitCast, CI.getType());
2455
81
  }
2456
775
2457
775
  return commonPointerCastTransforms(CI);
2458
775
}