1 //===-- IntrinsicLowering.cpp - Intrinsic Lowering default implementation -===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
10 // This file implements the IntrinsicLowering class.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Constants.h"
15 #include "llvm/DerivedTypes.h"
16 #include "llvm/Module.h"
17 #include "llvm/Instructions.h"
18 #include "llvm/Type.h"
19 #include "llvm/CodeGen/IntrinsicLowering.h"
20 #include "llvm/Support/Streams.h"
21 #include "llvm/Target/TargetData.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/STLExtras.h"
26 template <class ArgIt>
27 static void EnsureFunctionExists(Module &M, const char *Name,
28 ArgIt ArgBegin, ArgIt ArgEnd,
30 // Insert a correctly-typed definition now.
31 std::vector<const Type *> ParamTys;
32 for (ArgIt I = ArgBegin; I != ArgEnd; ++I)
33 ParamTys.push_back(I->getType());
34 M.getOrInsertFunction(Name, FunctionType::get(RetTy, ParamTys, false));
37 /// ReplaceCallWith - This function is used when we want to lower an intrinsic
38 /// call to a call of an external function. This handles hard cases such as
39 /// when there was already a prototype for the external function, and if that
40 /// prototype doesn't match the arguments we expect to pass in.
41 template <class ArgIt>
42 static CallInst *ReplaceCallWith(const char *NewFn, CallInst *CI,
43 ArgIt ArgBegin, ArgIt ArgEnd,
44 const Type *RetTy, Constant *&FCache) {
46 // If we haven't already looked up this function, check to see if the
47 // program already contains a function with this name.
48 Module *M = CI->getParent()->getParent()->getParent();
49 // Get or insert the definition now.
50 std::vector<const Type *> ParamTys;
51 for (ArgIt I = ArgBegin; I != ArgEnd; ++I)
52 ParamTys.push_back((*I)->getType());
53 FCache = M->getOrInsertFunction(NewFn,
54 FunctionType::get(RetTy, ParamTys, false));
57 SmallVector<Value *, 8> Args(ArgBegin, ArgEnd);
58 CallInst *NewCI = new CallInst(FCache, Args.begin(), Args.end(),
61 CI->replaceAllUsesWith(NewCI);
65 void IntrinsicLowering::AddPrototypes(Module &M) {
66 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
67 if (I->isDeclaration() && !I->use_empty())
68 switch (I->getIntrinsicID()) {
70 case Intrinsic::setjmp:
71 EnsureFunctionExists(M, "setjmp", I->arg_begin(), I->arg_end(),
74 case Intrinsic::longjmp:
75 EnsureFunctionExists(M, "longjmp", I->arg_begin(), I->arg_end(),
78 case Intrinsic::siglongjmp:
79 EnsureFunctionExists(M, "abort", I->arg_end(), I->arg_end(),
82 case Intrinsic::memcpy_i32:
83 case Intrinsic::memcpy_i64:
84 M.getOrInsertFunction("memcpy", PointerType::get(Type::Int8Ty),
85 PointerType::get(Type::Int8Ty),
86 PointerType::get(Type::Int8Ty),
87 TD.getIntPtrType(), (Type *)0);
89 case Intrinsic::memmove_i32:
90 case Intrinsic::memmove_i64:
91 M.getOrInsertFunction("memmove", PointerType::get(Type::Int8Ty),
92 PointerType::get(Type::Int8Ty),
93 PointerType::get(Type::Int8Ty),
94 TD.getIntPtrType(), (Type *)0);
96 case Intrinsic::memset_i32:
97 case Intrinsic::memset_i64:
98 M.getOrInsertFunction("memset", PointerType::get(Type::Int8Ty),
99 PointerType::get(Type::Int8Ty), Type::Int32Ty,
100 TD.getIntPtrType(), (Type *)0);
102 case Intrinsic::sqrt:
103 switch((int)I->arg_begin()->getType()->getTypeID()) {
104 case Type::FloatTyID:
105 EnsureFunctionExists(M, "sqrtf", I->arg_begin(), I->arg_end(),
107 case Type::DoubleTyID:
108 EnsureFunctionExists(M, "sqrt", I->arg_begin(), I->arg_end(),
110 case Type::X86_FP80TyID:
111 case Type::FP128TyID:
112 case Type::PPC_FP128TyID:
113 EnsureFunctionExists(M, "sqrtl", I->arg_begin(), I->arg_end(),
114 I->arg_begin()->getType());
120 /// LowerBSWAP - Emit the code to lower bswap of V before the specified
122 static Value *LowerBSWAP(Value *V, Instruction *IP) {
123 assert(V->getType()->isInteger() && "Can't bswap a non-integer type!");
125 unsigned BitSize = V->getType()->getPrimitiveSizeInBits();
128 default: assert(0 && "Unhandled type size of value to byteswap!");
130 Value *Tmp1 = BinaryOperator::createShl(V,
131 ConstantInt::get(V->getType(),8),"bswap.2",IP);
132 Value *Tmp2 = BinaryOperator::createLShr(V,
133 ConstantInt::get(V->getType(),8),"bswap.1",IP);
134 V = BinaryOperator::createOr(Tmp1, Tmp2, "bswap.i16", IP);
138 Value *Tmp4 = BinaryOperator::createShl(V,
139 ConstantInt::get(V->getType(),24),"bswap.4", IP);
140 Value *Tmp3 = BinaryOperator::createShl(V,
141 ConstantInt::get(V->getType(),8),"bswap.3",IP);
142 Value *Tmp2 = BinaryOperator::createLShr(V,
143 ConstantInt::get(V->getType(),8),"bswap.2",IP);
144 Value *Tmp1 = BinaryOperator::createLShr(V,
145 ConstantInt::get(V->getType(),24),"bswap.1", IP);
146 Tmp3 = BinaryOperator::createAnd(Tmp3,
147 ConstantInt::get(Type::Int32Ty, 0xFF0000),
149 Tmp2 = BinaryOperator::createAnd(Tmp2,
150 ConstantInt::get(Type::Int32Ty, 0xFF00),
152 Tmp4 = BinaryOperator::createOr(Tmp4, Tmp3, "bswap.or1", IP);
153 Tmp2 = BinaryOperator::createOr(Tmp2, Tmp1, "bswap.or2", IP);
154 V = BinaryOperator::createOr(Tmp4, Tmp2, "bswap.i32", IP);
158 Value *Tmp8 = BinaryOperator::createShl(V,
159 ConstantInt::get(V->getType(),56),"bswap.8", IP);
160 Value *Tmp7 = BinaryOperator::createShl(V,
161 ConstantInt::get(V->getType(),40),"bswap.7", IP);
162 Value *Tmp6 = BinaryOperator::createShl(V,
163 ConstantInt::get(V->getType(),24),"bswap.6", IP);
164 Value *Tmp5 = BinaryOperator::createShl(V,
165 ConstantInt::get(V->getType(),8),"bswap.5", IP);
166 Value* Tmp4 = BinaryOperator::createLShr(V,
167 ConstantInt::get(V->getType(),8),"bswap.4", IP);
168 Value* Tmp3 = BinaryOperator::createLShr(V,
169 ConstantInt::get(V->getType(),24),"bswap.3", IP);
170 Value* Tmp2 = BinaryOperator::createLShr(V,
171 ConstantInt::get(V->getType(),40),"bswap.2", IP);
172 Value* Tmp1 = BinaryOperator::createLShr(V,
173 ConstantInt::get(V->getType(),56),"bswap.1", IP);
174 Tmp7 = BinaryOperator::createAnd(Tmp7,
175 ConstantInt::get(Type::Int64Ty,
176 0xFF000000000000ULL),
178 Tmp6 = BinaryOperator::createAnd(Tmp6,
179 ConstantInt::get(Type::Int64Ty, 0xFF0000000000ULL),
181 Tmp5 = BinaryOperator::createAnd(Tmp5,
182 ConstantInt::get(Type::Int64Ty, 0xFF00000000ULL),
184 Tmp4 = BinaryOperator::createAnd(Tmp4,
185 ConstantInt::get(Type::Int64Ty, 0xFF000000ULL),
187 Tmp3 = BinaryOperator::createAnd(Tmp3,
188 ConstantInt::get(Type::Int64Ty, 0xFF0000ULL),
190 Tmp2 = BinaryOperator::createAnd(Tmp2,
191 ConstantInt::get(Type::Int64Ty, 0xFF00ULL),
193 Tmp8 = BinaryOperator::createOr(Tmp8, Tmp7, "bswap.or1", IP);
194 Tmp6 = BinaryOperator::createOr(Tmp6, Tmp5, "bswap.or2", IP);
195 Tmp4 = BinaryOperator::createOr(Tmp4, Tmp3, "bswap.or3", IP);
196 Tmp2 = BinaryOperator::createOr(Tmp2, Tmp1, "bswap.or4", IP);
197 Tmp8 = BinaryOperator::createOr(Tmp8, Tmp6, "bswap.or5", IP);
198 Tmp4 = BinaryOperator::createOr(Tmp4, Tmp2, "bswap.or6", IP);
199 V = BinaryOperator::createOr(Tmp8, Tmp4, "bswap.i64", IP);
206 /// LowerCTPOP - Emit the code to lower ctpop of V before the specified
208 static Value *LowerCTPOP(Value *V, Instruction *IP) {
209 assert(V->getType()->isInteger() && "Can't ctpop a non-integer type!");
211 static const uint64_t MaskValues[6] = {
212 0x5555555555555555ULL, 0x3333333333333333ULL,
213 0x0F0F0F0F0F0F0F0FULL, 0x00FF00FF00FF00FFULL,
214 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL
217 unsigned BitSize = V->getType()->getPrimitiveSizeInBits();
218 unsigned WordSize = (BitSize + 63) / 64;
219 Value *Count = ConstantInt::get(V->getType(), 0);
221 for (unsigned n = 0; n < WordSize; ++n) {
222 Value *PartValue = V;
223 for (unsigned i = 1, ct = 0; i < (BitSize>64 ? 64 : BitSize);
225 Value *MaskCst = ConstantInt::get(V->getType(), MaskValues[ct]);
226 Value *LHS = BinaryOperator::createAnd(
227 PartValue, MaskCst, "cppop.and1", IP);
228 Value *VShift = BinaryOperator::createLShr(PartValue,
229 ConstantInt::get(V->getType(), i), "ctpop.sh", IP);
230 Value *RHS = BinaryOperator::createAnd(VShift, MaskCst, "cppop.and2", IP);
231 PartValue = BinaryOperator::createAdd(LHS, RHS, "ctpop.step", IP);
233 Count = BinaryOperator::createAdd(PartValue, Count, "ctpop.part", IP);
235 V = BinaryOperator::createLShr(V, ConstantInt::get(V->getType(), 64),
236 "ctpop.part.sh", IP);
244 /// LowerCTLZ - Emit the code to lower ctlz of V before the specified
246 static Value *LowerCTLZ(Value *V, Instruction *IP) {
248 unsigned BitSize = V->getType()->getPrimitiveSizeInBits();
249 for (unsigned i = 1; i < BitSize; i <<= 1) {
250 Value *ShVal = ConstantInt::get(V->getType(), i);
251 ShVal = BinaryOperator::createLShr(V, ShVal, "ctlz.sh", IP);
252 V = BinaryOperator::createOr(V, ShVal, "ctlz.step", IP);
255 V = BinaryOperator::createNot(V, "", IP);
256 return LowerCTPOP(V, IP);
259 /// Convert the llvm.part.select.iX.iY intrinsic. This intrinsic takes
260 /// three integer arguments. The first argument is the Value from which the
261 /// bits will be selected. It may be of any bit width. The second and third
262 /// arguments specify a range of bits to select with the second argument
263 /// specifying the low bit and the third argument specifying the high bit. Both
264 /// must be type i32. The result is the corresponding selected bits from the
265 /// Value in the same width as the Value (first argument). If the low bit index
266 /// is higher than the high bit index then the inverse selection is done and
267 /// the bits are returned in inverse order.
268 /// @brief Lowering of llvm.part.select intrinsic.
269 static Instruction *LowerPartSelect(CallInst *CI) {
270 // Make sure we're dealing with a part select intrinsic here
271 Function *F = CI->getCalledFunction();
272 const FunctionType *FT = F->getFunctionType();
273 if (!F->isDeclaration() || !FT->getReturnType()->isInteger() ||
274 FT->getNumParams() != 3 || !FT->getParamType(0)->isInteger() ||
275 !FT->getParamType(1)->isInteger() || !FT->getParamType(2)->isInteger())
278 // Get the intrinsic implementation function by converting all the . to _
279 // in the intrinsic's function name and then reconstructing the function
281 std::string Name(F->getName());
282 for (unsigned i = 4; i < Name.length(); ++i)
285 Module* M = F->getParent();
286 F = cast<Function>(M->getOrInsertFunction(Name, FT));
287 F->setLinkage(GlobalValue::WeakLinkage);
289 // If we haven't defined the impl function yet, do so now
290 if (F->isDeclaration()) {
292 // Get the arguments to the function
293 Function::arg_iterator args = F->arg_begin();
294 Value* Val = args++; Val->setName("Val");
295 Value* Lo = args++; Lo->setName("Lo");
296 Value* Hi = args++; Hi->setName("High");
298 // We want to select a range of bits here such that [Hi, Lo] is shifted
299 // down to the low bits. However, it is quite possible that Hi is smaller
300 // than Lo in which case the bits have to be reversed.
302 // Create the blocks we will need for the two cases (forward, reverse)
303 BasicBlock* CurBB = new BasicBlock("entry", F);
304 BasicBlock *RevSize = new BasicBlock("revsize", CurBB->getParent());
305 BasicBlock *FwdSize = new BasicBlock("fwdsize", CurBB->getParent());
306 BasicBlock *Compute = new BasicBlock("compute", CurBB->getParent());
307 BasicBlock *Reverse = new BasicBlock("reverse", CurBB->getParent());
308 BasicBlock *RsltBlk = new BasicBlock("result", CurBB->getParent());
310 // Cast Hi and Lo to the size of Val so the widths are all the same
311 if (Hi->getType() != Val->getType())
312 Hi = CastInst::createIntegerCast(Hi, Val->getType(), false,
314 if (Lo->getType() != Val->getType())
315 Lo = CastInst::createIntegerCast(Lo, Val->getType(), false,
318 // Compute a few things that both cases will need, up front.
319 Constant* Zero = ConstantInt::get(Val->getType(), 0);
320 Constant* One = ConstantInt::get(Val->getType(), 1);
321 Constant* AllOnes = ConstantInt::getAllOnesValue(Val->getType());
323 // Compare the Hi and Lo bit positions. This is used to determine
324 // which case we have (forward or reverse)
325 ICmpInst *Cmp = new ICmpInst(ICmpInst::ICMP_ULT, Hi, Lo, "less",CurBB);
326 new BranchInst(RevSize, FwdSize, Cmp, CurBB);
328 // First, copmute the number of bits in the forward case.
329 Instruction* FBitSize =
330 BinaryOperator::createSub(Hi, Lo,"fbits", FwdSize);
331 new BranchInst(Compute, FwdSize);
333 // Second, compute the number of bits in the reverse case.
334 Instruction* RBitSize =
335 BinaryOperator::createSub(Lo, Hi, "rbits", RevSize);
336 new BranchInst(Compute, RevSize);
338 // Now, compute the bit range. Start by getting the bitsize and the shift
339 // amount (either Hi or Lo) from PHI nodes. Then we compute a mask for
340 // the number of bits we want in the range. We shift the bits down to the
341 // least significant bits, apply the mask to zero out unwanted high bits,
342 // and we have computed the "forward" result. It may still need to be
345 // Get the BitSize from one of the two subtractions
346 PHINode *BitSize = new PHINode(Val->getType(), "bits", Compute);
347 BitSize->reserveOperandSpace(2);
348 BitSize->addIncoming(FBitSize, FwdSize);
349 BitSize->addIncoming(RBitSize, RevSize);
351 // Get the ShiftAmount as the smaller of Hi/Lo
352 PHINode *ShiftAmt = new PHINode(Val->getType(), "shiftamt", Compute);
353 ShiftAmt->reserveOperandSpace(2);
354 ShiftAmt->addIncoming(Lo, FwdSize);
355 ShiftAmt->addIncoming(Hi, RevSize);
357 // Increment the bit size
358 Instruction *BitSizePlusOne =
359 BinaryOperator::createAdd(BitSize, One, "bits", Compute);
361 // Create a Mask to zero out the high order bits.
363 BinaryOperator::createShl(AllOnes, BitSizePlusOne, "mask", Compute);
364 Mask = BinaryOperator::createNot(Mask, "mask", Compute);
366 // Shift the bits down and apply the mask
368 BinaryOperator::createLShr(Val, ShiftAmt, "fres", Compute);
369 FRes = BinaryOperator::createAnd(FRes, Mask, "fres", Compute);
370 new BranchInst(Reverse, RsltBlk, Cmp, Compute);
372 // In the Reverse block we have the mask already in FRes but we must reverse
373 // it by shifting FRes bits right and putting them in RRes by shifting them
376 // First set up our loop counters
377 PHINode *Count = new PHINode(Val->getType(), "count", Reverse);
378 Count->reserveOperandSpace(2);
379 Count->addIncoming(BitSizePlusOne, Compute);
381 // Next, get the value that we are shifting.
382 PHINode *BitsToShift = new PHINode(Val->getType(), "val", Reverse);
383 BitsToShift->reserveOperandSpace(2);
384 BitsToShift->addIncoming(FRes, Compute);
386 // Finally, get the result of the last computation
387 PHINode *RRes = new PHINode(Val->getType(), "rres", Reverse);
388 RRes->reserveOperandSpace(2);
389 RRes->addIncoming(Zero, Compute);
391 // Decrement the counter
392 Instruction *Decr = BinaryOperator::createSub(Count, One, "decr", Reverse);
393 Count->addIncoming(Decr, Reverse);
395 // Compute the Bit that we want to move
397 BinaryOperator::createAnd(BitsToShift, One, "bit", Reverse);
399 // Compute the new value for next iteration.
400 Instruction *NewVal =
401 BinaryOperator::createLShr(BitsToShift, One, "rshift", Reverse);
402 BitsToShift->addIncoming(NewVal, Reverse);
404 // Shift the bit into the low bits of the result.
405 Instruction *NewRes =
406 BinaryOperator::createShl(RRes, One, "lshift", Reverse);
407 NewRes = BinaryOperator::createOr(NewRes, Bit, "addbit", Reverse);
408 RRes->addIncoming(NewRes, Reverse);
410 // Terminate loop if we've moved all the bits.
412 new ICmpInst(ICmpInst::ICMP_EQ, Decr, Zero, "cond", Reverse);
413 new BranchInst(RsltBlk, Reverse, Cond, Reverse);
415 // Finally, in the result block, select one of the two results with a PHI
416 // node and return the result;
418 PHINode *BitSelect = new PHINode(Val->getType(), "part_select", CurBB);
419 BitSelect->reserveOperandSpace(2);
420 BitSelect->addIncoming(FRes, Compute);
421 BitSelect->addIncoming(NewRes, Reverse);
422 new ReturnInst(BitSelect, CurBB);
425 // Return a call to the implementation function
431 return new CallInst(F, Args, array_endof(Args), CI->getName(), CI);
434 /// Convert the llvm.part.set.iX.iY.iZ intrinsic. This intrinsic takes
435 /// four integer arguments (iAny %Value, iAny %Replacement, i32 %Low, i32 %High)
436 /// The first two arguments can be any bit width. The result is the same width
437 /// as %Value. The operation replaces bits between %Low and %High with the value
438 /// in %Replacement. If %Replacement is not the same width, it is truncated or
439 /// zero extended as appropriate to fit the bits being replaced. If %Low is
440 /// greater than %High then the inverse set of bits are replaced.
441 /// @brief Lowering of llvm.bit.part.set intrinsic.
442 static Instruction *LowerPartSet(CallInst *CI) {
443 // Make sure we're dealing with a part select intrinsic here
444 Function *F = CI->getCalledFunction();
445 const FunctionType *FT = F->getFunctionType();
446 if (!F->isDeclaration() || !FT->getReturnType()->isInteger() ||
447 FT->getNumParams() != 4 || !FT->getParamType(0)->isInteger() ||
448 !FT->getParamType(1)->isInteger() || !FT->getParamType(2)->isInteger() ||
449 !FT->getParamType(3)->isInteger())
452 // Get the intrinsic implementation function by converting all the . to _
453 // in the intrinsic's function name and then reconstructing the function
455 std::string Name(F->getName());
456 for (unsigned i = 4; i < Name.length(); ++i)
459 Module* M = F->getParent();
460 F = cast<Function>(M->getOrInsertFunction(Name, FT));
461 F->setLinkage(GlobalValue::WeakLinkage);
463 // If we haven't defined the impl function yet, do so now
464 if (F->isDeclaration()) {
465 // Get the arguments for the function.
466 Function::arg_iterator args = F->arg_begin();
467 Value* Val = args++; Val->setName("Val");
468 Value* Rep = args++; Rep->setName("Rep");
469 Value* Lo = args++; Lo->setName("Lo");
470 Value* Hi = args++; Hi->setName("Hi");
472 // Get some types we need
473 const IntegerType* ValTy = cast<IntegerType>(Val->getType());
474 const IntegerType* RepTy = cast<IntegerType>(Rep->getType());
475 uint32_t ValBits = ValTy->getBitWidth();
476 uint32_t RepBits = RepTy->getBitWidth();
478 // Constant Definitions
479 ConstantInt* RepBitWidth = ConstantInt::get(Type::Int32Ty, RepBits);
480 ConstantInt* RepMask = ConstantInt::getAllOnesValue(RepTy);
481 ConstantInt* ValMask = ConstantInt::getAllOnesValue(ValTy);
482 ConstantInt* One = ConstantInt::get(Type::Int32Ty, 1);
483 ConstantInt* ValOne = ConstantInt::get(ValTy, 1);
484 ConstantInt* Zero = ConstantInt::get(Type::Int32Ty, 0);
485 ConstantInt* ValZero = ConstantInt::get(ValTy, 0);
487 // Basic blocks we fill in below.
488 BasicBlock* entry = new BasicBlock("entry", F, 0);
489 BasicBlock* large = new BasicBlock("large", F, 0);
490 BasicBlock* small = new BasicBlock("small", F, 0);
491 BasicBlock* reverse = new BasicBlock("reverse", F, 0);
492 BasicBlock* result = new BasicBlock("result", F, 0);
494 // BASIC BLOCK: entry
495 // First, get the number of bits that we're placing as an i32
496 ICmpInst* is_forward =
497 new ICmpInst(ICmpInst::ICMP_ULT, Lo, Hi, "", entry);
498 SelectInst* Hi_pn = new SelectInst(is_forward, Hi, Lo, "", entry);
499 SelectInst* Lo_pn = new SelectInst(is_forward, Lo, Hi, "", entry);
500 BinaryOperator* NumBits = BinaryOperator::createSub(Hi_pn, Lo_pn, "",entry);
501 NumBits = BinaryOperator::createAdd(NumBits, One, "", entry);
502 // Now, convert Lo and Hi to ValTy bit width
504 Lo = new ZExtInst(Lo_pn, ValTy, "", entry);
505 } else if (ValBits < 32) {
506 Lo = new TruncInst(Lo_pn, ValTy, "", entry);
508 // Determine if the replacement bits are larger than the number of bits we
509 // are replacing and deal with it.
511 new ICmpInst(ICmpInst::ICMP_ULT, NumBits, RepBitWidth, "", entry);
512 new BranchInst(large, small, is_large, entry);
514 // BASIC BLOCK: large
515 Instruction* MaskBits =
516 BinaryOperator::createSub(RepBitWidth, NumBits, "", large);
517 MaskBits = CastInst::createIntegerCast(MaskBits, RepMask->getType(),
519 BinaryOperator* Mask1 =
520 BinaryOperator::createLShr(RepMask, MaskBits, "", large);
521 BinaryOperator* Rep2 = BinaryOperator::createAnd(Mask1, Rep, "", large);
522 new BranchInst(small, large);
524 // BASIC BLOCK: small
525 PHINode* Rep3 = new PHINode(RepTy, "", small);
526 Rep3->reserveOperandSpace(2);
527 Rep3->addIncoming(Rep2, large);
528 Rep3->addIncoming(Rep, entry);
530 if (ValBits > RepBits)
531 Rep4 = new ZExtInst(Rep3, ValTy, "", small);
532 else if (ValBits < RepBits)
533 Rep4 = new TruncInst(Rep3, ValTy, "", small);
534 new BranchInst(result, reverse, is_forward, small);
536 // BASIC BLOCK: reverse (reverses the bits of the replacement)
537 // Set up our loop counter as a PHI so we can decrement on each iteration.
538 // We will loop for the number of bits in the replacement value.
539 PHINode *Count = new PHINode(Type::Int32Ty, "count", reverse);
540 Count->reserveOperandSpace(2);
541 Count->addIncoming(NumBits, small);
543 // Get the value that we are shifting bits out of as a PHI because
544 // we'll change this with each iteration.
545 PHINode *BitsToShift = new PHINode(Val->getType(), "val", reverse);
546 BitsToShift->reserveOperandSpace(2);
547 BitsToShift->addIncoming(Rep4, small);
549 // Get the result of the last computation or zero on first iteration
550 PHINode *RRes = new PHINode(Val->getType(), "rres", reverse);
551 RRes->reserveOperandSpace(2);
552 RRes->addIncoming(ValZero, small);
554 // Decrement the loop counter by one
555 Instruction *Decr = BinaryOperator::createSub(Count, One, "", reverse);
556 Count->addIncoming(Decr, reverse);
558 // Get the bit that we want to move into the result
559 Value *Bit = BinaryOperator::createAnd(BitsToShift, ValOne, "", reverse);
561 // Compute the new value of the bits to shift for the next iteration.
562 Value *NewVal = BinaryOperator::createLShr(BitsToShift, ValOne,"", reverse);
563 BitsToShift->addIncoming(NewVal, reverse);
565 // Shift the bit we extracted into the low bit of the result.
566 Instruction *NewRes = BinaryOperator::createShl(RRes, ValOne, "", reverse);
567 NewRes = BinaryOperator::createOr(NewRes, Bit, "", reverse);
568 RRes->addIncoming(NewRes, reverse);
570 // Terminate loop if we've moved all the bits.
571 ICmpInst *Cond = new ICmpInst(ICmpInst::ICMP_EQ, Decr, Zero, "", reverse);
572 new BranchInst(result, reverse, Cond, reverse);
574 // BASIC BLOCK: result
575 PHINode *Rplcmnt = new PHINode(Val->getType(), "", result);
576 Rplcmnt->reserveOperandSpace(2);
577 Rplcmnt->addIncoming(NewRes, reverse);
578 Rplcmnt->addIncoming(Rep4, small);
579 Value* t0 = CastInst::createIntegerCast(NumBits,ValTy,false,"",result);
580 Value* t1 = BinaryOperator::createShl(ValMask, Lo, "", result);
581 Value* t2 = BinaryOperator::createNot(t1, "", result);
582 Value* t3 = BinaryOperator::createShl(t1, t0, "", result);
583 Value* t4 = BinaryOperator::createOr(t2, t3, "", result);
584 Value* t5 = BinaryOperator::createAnd(t4, Val, "", result);
585 Value* t6 = BinaryOperator::createShl(Rplcmnt, Lo, "", result);
586 Value* Rslt = BinaryOperator::createOr(t5, t6, "part_set", result);
587 new ReturnInst(Rslt, result);
590 // Return a call to the implementation function
597 return new CallInst(F, Args, array_endof(Args), CI->getName(), CI);
601 void IntrinsicLowering::LowerIntrinsicCall(CallInst *CI) {
602 Function *Callee = CI->getCalledFunction();
603 assert(Callee && "Cannot lower an indirect call!");
605 switch (Callee->getIntrinsicID()) {
606 case Intrinsic::not_intrinsic:
607 cerr << "Cannot lower a call to a non-intrinsic function '"
608 << Callee->getName() << "'!\n";
611 cerr << "Error: Code generator does not support intrinsic function '"
612 << Callee->getName() << "'!\n";
615 // The setjmp/longjmp intrinsics should only exist in the code if it was
616 // never optimized (ie, right out of the CFE), or if it has been hacked on
617 // by the lowerinvoke pass. In both cases, the right thing to do is to
618 // convert the call to an explicit setjmp or longjmp call.
619 case Intrinsic::setjmp: {
620 static Constant *SetjmpFCache = 0;
621 Value *V = ReplaceCallWith("setjmp", CI, CI->op_begin()+1, CI->op_end(),
622 Type::Int32Ty, SetjmpFCache);
623 if (CI->getType() != Type::VoidTy)
624 CI->replaceAllUsesWith(V);
627 case Intrinsic::sigsetjmp:
628 if (CI->getType() != Type::VoidTy)
629 CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
632 case Intrinsic::longjmp: {
633 static Constant *LongjmpFCache = 0;
634 ReplaceCallWith("longjmp", CI, CI->op_begin()+1, CI->op_end(),
635 Type::VoidTy, LongjmpFCache);
639 case Intrinsic::siglongjmp: {
640 // Insert the call to abort
641 static Constant *AbortFCache = 0;
642 ReplaceCallWith("abort", CI, CI->op_end(), CI->op_end(),
643 Type::VoidTy, AbortFCache);
646 case Intrinsic::ctpop:
647 CI->replaceAllUsesWith(LowerCTPOP(CI->getOperand(1), CI));
650 case Intrinsic::bswap:
651 CI->replaceAllUsesWith(LowerBSWAP(CI->getOperand(1), CI));
654 case Intrinsic::ctlz:
655 CI->replaceAllUsesWith(LowerCTLZ(CI->getOperand(1), CI));
658 case Intrinsic::cttz: {
659 // cttz(x) -> ctpop(~X & (X-1))
660 Value *Src = CI->getOperand(1);
661 Value *NotSrc = BinaryOperator::createNot(Src, Src->getName()+".not", CI);
662 Value *SrcM1 = ConstantInt::get(Src->getType(), 1);
663 SrcM1 = BinaryOperator::createSub(Src, SrcM1, "", CI);
664 Src = LowerCTPOP(BinaryOperator::createAnd(NotSrc, SrcM1, "", CI), CI);
665 CI->replaceAllUsesWith(Src);
669 case Intrinsic::part_select:
670 CI->replaceAllUsesWith(LowerPartSelect(CI));
673 case Intrinsic::part_set:
674 CI->replaceAllUsesWith(LowerPartSet(CI));
677 case Intrinsic::stacksave:
678 case Intrinsic::stackrestore: {
679 static bool Warned = false;
681 cerr << "WARNING: this target does not support the llvm.stack"
682 << (Callee->getIntrinsicID() == Intrinsic::stacksave ?
683 "save" : "restore") << " intrinsic.\n";
685 if (Callee->getIntrinsicID() == Intrinsic::stacksave)
686 CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
690 case Intrinsic::returnaddress:
691 case Intrinsic::frameaddress:
692 cerr << "WARNING: this target does not support the llvm."
693 << (Callee->getIntrinsicID() == Intrinsic::returnaddress ?
694 "return" : "frame") << "address intrinsic.\n";
695 CI->replaceAllUsesWith(ConstantPointerNull::get(
696 cast<PointerType>(CI->getType())));
699 case Intrinsic::prefetch:
700 break; // Simply strip out prefetches on unsupported architectures
702 case Intrinsic::pcmarker:
703 break; // Simply strip out pcmarker on unsupported architectures
704 case Intrinsic::readcyclecounter: {
705 cerr << "WARNING: this target does not support the llvm.readcyclecoun"
706 << "ter intrinsic. It is being lowered to a constant 0\n";
707 CI->replaceAllUsesWith(ConstantInt::get(Type::Int64Ty, 0));
711 case Intrinsic::dbg_stoppoint:
712 case Intrinsic::dbg_region_start:
713 case Intrinsic::dbg_region_end:
714 case Intrinsic::dbg_func_start:
715 case Intrinsic::dbg_declare:
716 break; // Simply strip out debugging intrinsics
718 case Intrinsic::eh_exception:
719 case Intrinsic::eh_selector_i32:
720 case Intrinsic::eh_selector_i64:
721 CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
724 case Intrinsic::eh_typeid_for_i32:
725 case Intrinsic::eh_typeid_for_i64:
726 // Return something different to eh_selector.
727 CI->replaceAllUsesWith(ConstantInt::get(CI->getType(), 1));
730 case Intrinsic::var_annotation:
731 break; // Strip out annotate intrinsic
733 case Intrinsic::memcpy_i32:
734 case Intrinsic::memcpy_i64: {
735 static Constant *MemcpyFCache = 0;
736 Value *Size = CI->getOperand(3);
737 const Type *IntPtr = TD.getIntPtrType();
738 if (Size->getType()->getPrimitiveSizeInBits() <
739 IntPtr->getPrimitiveSizeInBits())
740 Size = new ZExtInst(Size, IntPtr, "", CI);
741 else if (Size->getType()->getPrimitiveSizeInBits() >
742 IntPtr->getPrimitiveSizeInBits())
743 Size = new TruncInst(Size, IntPtr, "", CI);
745 Ops[0] = CI->getOperand(1);
746 Ops[1] = CI->getOperand(2);
748 ReplaceCallWith("memcpy", CI, Ops, Ops+3, CI->getOperand(1)->getType(),
752 case Intrinsic::memmove_i32:
753 case Intrinsic::memmove_i64: {
754 static Constant *MemmoveFCache = 0;
755 Value *Size = CI->getOperand(3);
756 const Type *IntPtr = TD.getIntPtrType();
757 if (Size->getType()->getPrimitiveSizeInBits() <
758 IntPtr->getPrimitiveSizeInBits())
759 Size = new ZExtInst(Size, IntPtr, "", CI);
760 else if (Size->getType()->getPrimitiveSizeInBits() >
761 IntPtr->getPrimitiveSizeInBits())
762 Size = new TruncInst(Size, IntPtr, "", CI);
764 Ops[0] = CI->getOperand(1);
765 Ops[1] = CI->getOperand(2);
767 ReplaceCallWith("memmove", CI, Ops, Ops+3, CI->getOperand(1)->getType(),
771 case Intrinsic::memset_i32:
772 case Intrinsic::memset_i64: {
773 static Constant *MemsetFCache = 0;
774 Value *Size = CI->getOperand(3);
775 const Type *IntPtr = TD.getIntPtrType();
776 if (Size->getType()->getPrimitiveSizeInBits() <
777 IntPtr->getPrimitiveSizeInBits())
778 Size = new ZExtInst(Size, IntPtr, "", CI);
779 else if (Size->getType()->getPrimitiveSizeInBits() >
780 IntPtr->getPrimitiveSizeInBits())
781 Size = new TruncInst(Size, IntPtr, "", CI);
783 Ops[0] = CI->getOperand(1);
784 // Extend the amount to i32.
785 Ops[1] = new ZExtInst(CI->getOperand(2), Type::Int32Ty, "", CI);
787 ReplaceCallWith("memset", CI, Ops, Ops+3, CI->getOperand(1)->getType(),
791 case Intrinsic::sqrt: {
792 static Constant *sqrtfFCache = 0;
793 static Constant *sqrtFCache = 0;
794 static Constant *sqrtLDCache = 0;
795 switch (CI->getOperand(1)->getType()->getTypeID()) {
796 default: assert(0 && "Invalid type in sqrt"); abort();
797 case Type::FloatTyID:
798 ReplaceCallWith("sqrtf", CI, CI->op_begin()+1, CI->op_end(),
799 Type::FloatTy, sqrtfFCache);
801 case Type::DoubleTyID:
802 ReplaceCallWith("sqrt", CI, CI->op_begin()+1, CI->op_end(),
803 Type::DoubleTy, sqrtFCache);
805 case Type::X86_FP80TyID:
806 case Type::FP128TyID:
807 case Type::PPC_FP128TyID:
808 ReplaceCallWith("sqrtl", CI, CI->op_begin()+1, CI->op_end(),
809 CI->getOperand(1)->getType(), sqrtLDCache);
816 assert(CI->use_empty() &&
817 "Lowering should have eliminated any uses of the intrinsic call!");
818 CI->eraseFromParent();