IntrinsicLowering.cpp revision b71fd7897f6b4500cdbe602c5a9907316750cf5a
1//===-- IntrinsicLowering.cpp - Intrinsic Lowering default implementation -===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the IntrinsicLowering class.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/CodeGen/IntrinsicLowering.h"
15#include "llvm/Constants.h"
16#include "llvm/DerivedTypes.h"
17#include "llvm/Module.h"
18#include "llvm/Instructions.h"
19#include "llvm/Type.h"
20#include <iostream>
21
22using namespace llvm;
23
24template <class ArgIt>
25static Function *EnsureFunctionExists(Module &M, const char *Name,
26                                      ArgIt ArgBegin, ArgIt ArgEnd,
27                                      const Type *RetTy) {
28  if (Function *F = M.getNamedFunction(Name)) return F;
29  // It doesn't already exist in the program, insert a new definition now.
30  std::vector<const Type *> ParamTys;
31  for (ArgIt I = ArgBegin; I != ArgEnd; ++I)
32    ParamTys.push_back(I->getType());
33  return M.getOrInsertFunction(Name, FunctionType::get(RetTy, ParamTys, false));
34}
35
36/// ReplaceCallWith - This function is used when we want to lower an intrinsic
37/// call to a call of an external function.  This handles hard cases such as
38/// when there was already a prototype for the external function, and if that
39/// prototype doesn't match the arguments we expect to pass in.
40template <class ArgIt>
41static CallInst *ReplaceCallWith(const char *NewFn, CallInst *CI,
42                                 ArgIt ArgBegin, ArgIt ArgEnd,
43                                 const Type *RetTy, Function *&FCache) {
44  if (!FCache) {
45    // If we haven't already looked up this function, check to see if the
46    // program already contains a function with this name.
47    Module *M = CI->getParent()->getParent()->getParent();
48    FCache = M->getNamedFunction(NewFn);
49    if (!FCache) {
50      // It doesn't already exist in the program, insert a new definition now.
51      std::vector<const Type *> ParamTys;
52      for (ArgIt I = ArgBegin; I != ArgEnd; ++I)
53        ParamTys.push_back((*I)->getType());
54      FCache = M->getOrInsertFunction(NewFn,
55                                     FunctionType::get(RetTy, ParamTys, false));
56    }
57   }
58
59  const FunctionType *FT = FCache->getFunctionType();
60  std::vector<Value*> Operands;
61  unsigned ArgNo = 0;
62  for (ArgIt I = ArgBegin; I != ArgEnd && ArgNo != FT->getNumParams();
63       ++I, ++ArgNo) {
64    Value *Arg = *I;
65    if (Arg->getType() != FT->getParamType(ArgNo))
66      Arg = new CastInst(Arg, FT->getParamType(ArgNo), Arg->getName(), CI);
67    Operands.push_back(Arg);
68  }
69  // Pass nulls into any additional arguments...
70  for (; ArgNo != FT->getNumParams(); ++ArgNo)
71    Operands.push_back(Constant::getNullValue(FT->getParamType(ArgNo)));
72
73  std::string Name = CI->getName(); CI->setName("");
74  if (FT->getReturnType() == Type::VoidTy) Name.clear();
75  CallInst *NewCI = new CallInst(FCache, Operands, Name, CI);
76  if (!CI->use_empty()) {
77    Value *V = NewCI;
78    if (CI->getType() != NewCI->getType())
79      V = new CastInst(NewCI, CI->getType(), Name, CI);
80    CI->replaceAllUsesWith(V);
81  }
82  return NewCI;
83}
84
85void IntrinsicLowering::AddPrototypes(Module &M) {
86  for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
87    if (I->isExternal() && !I->use_empty())
88      switch (I->getIntrinsicID()) {
89      default: break;
90      case Intrinsic::setjmp:
91        EnsureFunctionExists(M, "setjmp", I->arg_begin(), I->arg_end(),
92                             Type::IntTy);
93        break;
94      case Intrinsic::longjmp:
95        EnsureFunctionExists(M, "longjmp", I->arg_begin(), I->arg_end(),
96                             Type::VoidTy);
97        break;
98      case Intrinsic::siglongjmp:
99        EnsureFunctionExists(M, "abort", I->arg_end(), I->arg_end(),
100                             Type::VoidTy);
101        break;
102      case Intrinsic::memcpy_i32:
103      case Intrinsic::memcpy_i64:
104        EnsureFunctionExists(M, "memcpy", I->arg_begin(), --I->arg_end(),
105                             I->arg_begin()->getType());
106        break;
107      case Intrinsic::memmove_i32:
108      case Intrinsic::memmove_i64:
109        EnsureFunctionExists(M, "memmove", I->arg_begin(), --I->arg_end(),
110                             I->arg_begin()->getType());
111        break;
112      case Intrinsic::memset_i32:
113      case Intrinsic::memset_i64:
114        M.getOrInsertFunction("memset", PointerType::get(Type::SByteTy),
115                              PointerType::get(Type::SByteTy),
116                              Type::IntTy, (--(--I->arg_end()))->getType(),
117                              (Type *)0);
118        break;
119      case Intrinsic::isunordered_f32:
120      case Intrinsic::isunordered_f64:
121        EnsureFunctionExists(M, "isunordered", I->arg_begin(), I->arg_end(),
122                             Type::BoolTy);
123        break;
124      case Intrinsic::sqrt_f32:
125      case Intrinsic::sqrt_f64:
126        if(I->arg_begin()->getType() == Type::FloatTy)
127          EnsureFunctionExists(M, "sqrtf", I->arg_begin(), I->arg_end(),
128                               Type::FloatTy);
129        else
130          EnsureFunctionExists(M, "sqrt", I->arg_begin(), I->arg_end(),
131                               Type::DoubleTy);
132        break;
133      }
134}
135
136/// LowerBSWAP - Emit the code to lower bswap of V before the specified
137/// instruction IP.
138static Value *LowerBSWAP(Value *V, Instruction *IP) {
139  assert(V->getType()->isInteger() && "Can't bswap a non-integer type!");
140
141  unsigned BitSize = V->getType()->getPrimitiveSizeInBits();
142
143  switch(BitSize) {
144  default: assert(0 && "Unhandled type size of value to byteswap!");
145  case 16: {
146    Value *Tmp1 = new ShiftInst(Instruction::Shl, V,
147                                ConstantInt::get(Type::UByteTy,8),"bswap.2",IP);
148    Value *Tmp2 = new ShiftInst(Instruction::LShr, V,
149                                ConstantInt::get(Type::UByteTy,8),"bswap.1",IP);
150    V = BinaryOperator::createOr(Tmp1, Tmp2, "bswap.i16", IP);
151    break;
152  }
153  case 32: {
154    Value *Tmp4 = new ShiftInst(Instruction::Shl, V,
155                              ConstantInt::get(Type::UByteTy,24),"bswap.4", IP);
156    Value *Tmp3 = new ShiftInst(Instruction::Shl, V,
157                              ConstantInt::get(Type::UByteTy,8),"bswap.3",IP);
158    Value *Tmp2 = new ShiftInst(Instruction::LShr, V,
159                              ConstantInt::get(Type::UByteTy,8),"bswap.2",IP);
160    Value *Tmp1 = new ShiftInst(Instruction::LShr, V,
161                              ConstantInt::get(Type::UByteTy,24),"bswap.1", IP);
162    Tmp3 = BinaryOperator::createAnd(Tmp3,
163                                     ConstantInt::get(Type::UIntTy, 0xFF0000),
164                                     "bswap.and3", IP);
165    Tmp2 = BinaryOperator::createAnd(Tmp2,
166                                     ConstantInt::get(Type::UIntTy, 0xFF00),
167                                     "bswap.and2", IP);
168    Tmp4 = BinaryOperator::createOr(Tmp4, Tmp3, "bswap.or1", IP);
169    Tmp2 = BinaryOperator::createOr(Tmp2, Tmp1, "bswap.or2", IP);
170    V = BinaryOperator::createOr(Tmp4, Tmp3, "bswap.i32", IP);
171    break;
172  }
173  case 64: {
174    Value *Tmp8 = new ShiftInst(Instruction::Shl, V,
175                              ConstantInt::get(Type::UByteTy,56),"bswap.8", IP);
176    Value *Tmp7 = new ShiftInst(Instruction::Shl, V,
177                              ConstantInt::get(Type::UByteTy,40),"bswap.7", IP);
178    Value *Tmp6 = new ShiftInst(Instruction::Shl, V,
179                              ConstantInt::get(Type::UByteTy,24),"bswap.6", IP);
180    Value *Tmp5 = new ShiftInst(Instruction::Shl, V,
181                              ConstantInt::get(Type::UByteTy,8),"bswap.5", IP);
182    Value* Tmp4 = new ShiftInst(Instruction::LShr, V,
183                              ConstantInt::get(Type::UByteTy,8),"bswap.4", IP);
184    Value* Tmp3 = new ShiftInst(Instruction::LShr, V,
185                              ConstantInt::get(Type::UByteTy,24),"bswap.3", IP);
186    Value* Tmp2 = new ShiftInst(Instruction::LShr, V,
187                              ConstantInt::get(Type::UByteTy,40),"bswap.2", IP);
188    Value* Tmp1 = new ShiftInst(Instruction::LShr, V,
189                              ConstantInt::get(Type::UByteTy,56),"bswap.1", IP);
190    Tmp7 = BinaryOperator::createAnd(Tmp7,
191                             ConstantInt::get(Type::ULongTy,
192                               0xFF000000000000ULL),
193                             "bswap.and7", IP);
194    Tmp6 = BinaryOperator::createAnd(Tmp6,
195                             ConstantInt::get(Type::ULongTy, 0xFF0000000000ULL),
196                             "bswap.and6", IP);
197    Tmp5 = BinaryOperator::createAnd(Tmp5,
198                             ConstantInt::get(Type::ULongTy, 0xFF00000000ULL),
199                             "bswap.and5", IP);
200    Tmp4 = BinaryOperator::createAnd(Tmp4,
201                             ConstantInt::get(Type::ULongTy, 0xFF000000ULL),
202                             "bswap.and4", IP);
203    Tmp3 = BinaryOperator::createAnd(Tmp3,
204                             ConstantInt::get(Type::ULongTy, 0xFF0000ULL),
205                             "bswap.and3", IP);
206    Tmp2 = BinaryOperator::createAnd(Tmp2,
207                             ConstantInt::get(Type::ULongTy, 0xFF00ULL),
208                             "bswap.and2", IP);
209    Tmp8 = BinaryOperator::createOr(Tmp8, Tmp7, "bswap.or1", IP);
210    Tmp6 = BinaryOperator::createOr(Tmp6, Tmp5, "bswap.or2", IP);
211    Tmp4 = BinaryOperator::createOr(Tmp4, Tmp3, "bswap.or3", IP);
212    Tmp2 = BinaryOperator::createOr(Tmp2, Tmp1, "bswap.or4", IP);
213    Tmp8 = BinaryOperator::createOr(Tmp8, Tmp6, "bswap.or5", IP);
214    Tmp4 = BinaryOperator::createOr(Tmp4, Tmp2, "bswap.or6", IP);
215    V = BinaryOperator::createOr(Tmp8, Tmp4, "bswap.i64", IP);
216    break;
217  }
218  }
219  return V;
220}
221
222/// LowerCTPOP - Emit the code to lower ctpop of V before the specified
223/// instruction IP.
224static Value *LowerCTPOP(Value *V, Instruction *IP) {
225  assert(V->getType()->isInteger() && "Can't ctpop a non-integer type!");
226
227  static const uint64_t MaskValues[6] = {
228    0x5555555555555555ULL, 0x3333333333333333ULL,
229    0x0F0F0F0F0F0F0F0FULL, 0x00FF00FF00FF00FFULL,
230    0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL
231  };
232
233  unsigned BitSize = V->getType()->getPrimitiveSizeInBits();
234
235  for (unsigned i = 1, ct = 0; i != BitSize; i <<= 1, ++ct) {
236    Value *MaskCst =
237      ConstantExpr::getCast(ConstantInt::get(Type::ULongTy, MaskValues[ct]),
238                                             V->getType());
239    Value *LHS = BinaryOperator::createAnd(V, MaskCst, "cppop.and1", IP);
240    Value *VShift = new ShiftInst(Instruction::LShr, V,
241                      ConstantInt::get(Type::UByteTy, i), "ctpop.sh", IP);
242    Value *RHS = BinaryOperator::createAnd(VShift, MaskCst, "cppop.and2", IP);
243    V = BinaryOperator::createAdd(LHS, RHS, "ctpop.step", IP);
244  }
245
246  return V;
247}
248
249/// LowerCTLZ - Emit the code to lower ctlz of V before the specified
250/// instruction IP.
251static Value *LowerCTLZ(Value *V, Instruction *IP) {
252
253  unsigned BitSize = V->getType()->getPrimitiveSizeInBits();
254  for (unsigned i = 1; i != BitSize; i <<= 1) {
255    Value *ShVal = ConstantInt::get(Type::UByteTy, i);
256    ShVal = new ShiftInst(Instruction::LShr, V, ShVal, "ctlz.sh", IP);
257    V = BinaryOperator::createOr(V, ShVal, "ctlz.step", IP);
258  }
259
260  V = BinaryOperator::createNot(V, "", IP);
261  return LowerCTPOP(V, IP);
262}
263
264
265
266void IntrinsicLowering::LowerIntrinsicCall(CallInst *CI) {
267  Function *Callee = CI->getCalledFunction();
268  assert(Callee && "Cannot lower an indirect call!");
269
270  switch (Callee->getIntrinsicID()) {
271  case Intrinsic::not_intrinsic:
272    std::cerr << "Cannot lower a call to a non-intrinsic function '"
273              << Callee->getName() << "'!\n";
274    abort();
275  default:
276    std::cerr << "Error: Code generator does not support intrinsic function '"
277              << Callee->getName() << "'!\n";
278    abort();
279
280    // The setjmp/longjmp intrinsics should only exist in the code if it was
281    // never optimized (ie, right out of the CFE), or if it has been hacked on
282    // by the lowerinvoke pass.  In both cases, the right thing to do is to
283    // convert the call to an explicit setjmp or longjmp call.
284  case Intrinsic::setjmp: {
285    static Function *SetjmpFCache = 0;
286    Value *V = ReplaceCallWith("setjmp", CI, CI->op_begin()+1, CI->op_end(),
287                               Type::IntTy, SetjmpFCache);
288    if (CI->getType() != Type::VoidTy)
289      CI->replaceAllUsesWith(V);
290    break;
291  }
292  case Intrinsic::sigsetjmp:
293     if (CI->getType() != Type::VoidTy)
294       CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
295     break;
296
297  case Intrinsic::longjmp: {
298    static Function *LongjmpFCache = 0;
299    ReplaceCallWith("longjmp", CI, CI->op_begin()+1, CI->op_end(),
300                    Type::VoidTy, LongjmpFCache);
301    break;
302  }
303
304  case Intrinsic::siglongjmp: {
305    // Insert the call to abort
306    static Function *AbortFCache = 0;
307    ReplaceCallWith("abort", CI, CI->op_end(), CI->op_end(), Type::VoidTy,
308                    AbortFCache);
309    break;
310  }
311  case Intrinsic::ctpop_i8:
312  case Intrinsic::ctpop_i16:
313  case Intrinsic::ctpop_i32:
314  case Intrinsic::ctpop_i64:
315    CI->replaceAllUsesWith(LowerCTPOP(CI->getOperand(1), CI));
316    break;
317
318  case Intrinsic::bswap_i16:
319  case Intrinsic::bswap_i32:
320  case Intrinsic::bswap_i64:
321    CI->replaceAllUsesWith(LowerBSWAP(CI->getOperand(1), CI));
322    break;
323
324  case Intrinsic::ctlz_i8:
325  case Intrinsic::ctlz_i16:
326  case Intrinsic::ctlz_i32:
327  case Intrinsic::ctlz_i64:
328    CI->replaceAllUsesWith(LowerCTLZ(CI->getOperand(1), CI));
329    break;
330
331  case Intrinsic::cttz_i8:
332  case Intrinsic::cttz_i16:
333  case Intrinsic::cttz_i32:
334  case Intrinsic::cttz_i64: {
335    // cttz(x) -> ctpop(~X & (X-1))
336    Value *Src = CI->getOperand(1);
337    Value *NotSrc = BinaryOperator::createNot(Src, Src->getName()+".not", CI);
338    Value *SrcM1  = ConstantInt::get(Src->getType(), 1);
339    SrcM1 = BinaryOperator::createSub(Src, SrcM1, "", CI);
340    Src = LowerCTPOP(BinaryOperator::createAnd(NotSrc, SrcM1, "", CI), CI);
341    CI->replaceAllUsesWith(Src);
342    break;
343  }
344
345  case Intrinsic::stacksave:
346  case Intrinsic::stackrestore: {
347    static bool Warned = false;
348    if (!Warned)
349      std::cerr << "WARNING: this target does not support the llvm.stack"
350       << (Callee->getIntrinsicID() == Intrinsic::stacksave ?
351           "save" : "restore") << " intrinsic.\n";
352    Warned = true;
353    if (Callee->getIntrinsicID() == Intrinsic::stacksave)
354      CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
355    break;
356  }
357
358  case Intrinsic::returnaddress:
359  case Intrinsic::frameaddress:
360    std::cerr << "WARNING: this target does not support the llvm."
361              << (Callee->getIntrinsicID() == Intrinsic::returnaddress ?
362                  "return" : "frame") << "address intrinsic.\n";
363    CI->replaceAllUsesWith(ConstantPointerNull::get(
364                                            cast<PointerType>(CI->getType())));
365    break;
366
367  case Intrinsic::prefetch:
368    break;    // Simply strip out prefetches on unsupported architectures
369
370  case Intrinsic::pcmarker:
371    break;    // Simply strip out pcmarker on unsupported architectures
372  case Intrinsic::readcyclecounter: {
373    std::cerr << "WARNING: this target does not support the llvm.readcyclecoun"
374              << "ter intrinsic.  It is being lowered to a constant 0\n";
375    CI->replaceAllUsesWith(ConstantInt::get(Type::ULongTy, 0));
376    break;
377  }
378
379  case Intrinsic::dbg_stoppoint:
380  case Intrinsic::dbg_region_start:
381  case Intrinsic::dbg_region_end:
382  case Intrinsic::dbg_func_start:
383  case Intrinsic::dbg_declare:
384    break;    // Simply strip out debugging intrinsics
385
386  case Intrinsic::memcpy_i32:
387  case Intrinsic::memcpy_i64: {
388    // The memcpy intrinsic take an extra alignment argument that the memcpy
389    // libc function does not.
390    static Function *MemcpyFCache = 0;
391    ReplaceCallWith("memcpy", CI, CI->op_begin()+1, CI->op_end()-1,
392                    (*(CI->op_begin()+1))->getType(), MemcpyFCache);
393    break;
394  }
395  case Intrinsic::memmove_i32:
396  case Intrinsic::memmove_i64: {
397    // The memmove intrinsic take an extra alignment argument that the memmove
398    // libc function does not.
399    static Function *MemmoveFCache = 0;
400    ReplaceCallWith("memmove", CI, CI->op_begin()+1, CI->op_end()-1,
401                    (*(CI->op_begin()+1))->getType(), MemmoveFCache);
402    break;
403  }
404  case Intrinsic::memset_i32:
405  case Intrinsic::memset_i64: {
406    // The memset intrinsic take an extra alignment argument that the memset
407    // libc function does not.
408    static Function *MemsetFCache = 0;
409    ReplaceCallWith("memset", CI, CI->op_begin()+1, CI->op_end()-1,
410                    (*(CI->op_begin()+1))->getType(), MemsetFCache);
411    break;
412  }
413  case Intrinsic::isunordered_f32:
414  case Intrinsic::isunordered_f64: {
415    Value *L = CI->getOperand(1);
416    Value *R = CI->getOperand(2);
417
418    Value *LIsNan = new SetCondInst(Instruction::SetNE, L, L, "LIsNan", CI);
419    Value *RIsNan = new SetCondInst(Instruction::SetNE, R, R, "RIsNan", CI);
420    CI->replaceAllUsesWith(
421      BinaryOperator::create(Instruction::Or, LIsNan, RIsNan,
422                             "isunordered", CI));
423    break;
424  }
425  case Intrinsic::sqrt_f32:
426  case Intrinsic::sqrt_f64: {
427    static Function *sqrtFCache = 0;
428    static Function *sqrtfFCache = 0;
429    if(CI->getType() == Type::FloatTy)
430      ReplaceCallWith("sqrtf", CI, CI->op_begin()+1, CI->op_end(),
431                      Type::FloatTy, sqrtfFCache);
432    else
433      ReplaceCallWith("sqrt", CI, CI->op_begin()+1, CI->op_end(),
434                      Type::DoubleTy, sqrtFCache);
435    break;
436  }
437  }
438
439  assert(CI->use_empty() &&
440         "Lowering should have eliminated any uses of the intrinsic call!");
441  CI->eraseFromParent();
442}
443