3908e8aed68cb2e7284e15538793ccb5505ac9e2
[oota-llvm.git] / lib / VMCore / AutoUpgrade.cpp
1 //===-- AutoUpgrade.cpp - Implement auto-upgrade helper functions ---------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the auto-upgrade helper functions 
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/AutoUpgrade.h"
15 #include "llvm/Constants.h"
16 #include "llvm/Function.h"
17 #include "llvm/LLVMContext.h"
18 #include "llvm/Module.h"
19 #include "llvm/IntrinsicInst.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/Support/CallSite.h"
22 #include "llvm/Support/ErrorHandling.h"
23 #include "llvm/Support/IRBuilder.h"
24 #include <cstring>
25 using namespace llvm;
26
27
28 static bool UpgradeIntrinsicFunction1(Function *F, Function *&NewFn) {
29   assert(F && "Illegal to upgrade a non-existent Function.");
30
31   // Get the Function's name.
32   const std::string& Name = F->getName();
33
34   // Convenience
35   const FunctionType *FTy = F->getFunctionType();
36
37   // Quickly eliminate it, if it's not a candidate.
38   if (Name.length() <= 8 || Name[0] != 'l' || Name[1] != 'l' || 
39       Name[2] != 'v' || Name[3] != 'm' || Name[4] != '.')
40     return false;
41
42   Module *M = F->getParent();
43   switch (Name[5]) {
44   default: break;
45   case 'a':
46     // This upgrades the llvm.atomic.lcs, llvm.atomic.las, llvm.atomic.lss,
47     // and atomics with default address spaces to their new names to their new
48     // function name (e.g. llvm.atomic.add.i32 => llvm.atomic.add.i32.p0i32)
49     if (Name.compare(5,7,"atomic.",7) == 0) {
50       if (Name.compare(12,3,"lcs",3) == 0) {
51         std::string::size_type delim = Name.find('.',12);
52         F->setName("llvm.atomic.cmp.swap" + Name.substr(delim) +
53                    ".p0" + Name.substr(delim+1));
54         NewFn = F;
55         return true;
56       }
57       else if (Name.compare(12,3,"las",3) == 0) {
58         std::string::size_type delim = Name.find('.',12);
59         F->setName("llvm.atomic.load.add"+Name.substr(delim)
60                    + ".p0" + Name.substr(delim+1));
61         NewFn = F;
62         return true;
63       }
64       else if (Name.compare(12,3,"lss",3) == 0) {
65         std::string::size_type delim = Name.find('.',12);
66         F->setName("llvm.atomic.load.sub"+Name.substr(delim)
67                    + ".p0" + Name.substr(delim+1));
68         NewFn = F;
69         return true;
70       }
71       else if (Name.rfind(".p") == std::string::npos) {
72         // We don't have an address space qualifier so this has be upgraded
73         // to the new name.  Copy the type name at the end of the intrinsic
74         // and add to it
75         std::string::size_type delim = Name.find_last_of('.');
76         assert(delim != std::string::npos && "can not find type");
77         F->setName(Name + ".p0" + Name.substr(delim+1));
78         NewFn = F;
79         return true;
80       }
81     } else if (Name.compare(5, 9, "arm.neon.", 9) == 0) {
82       if (((Name.compare(14, 5, "vmovl", 5) == 0 ||
83             Name.compare(14, 5, "vaddl", 5) == 0 ||
84             Name.compare(14, 5, "vsubl", 5) == 0 ||
85             Name.compare(14, 5, "vaddw", 5) == 0 ||
86             Name.compare(14, 5, "vsubw", 5) == 0 ||
87             Name.compare(14, 5, "vmull", 5) == 0 ||
88             Name.compare(14, 5, "vmlal", 5) == 0 ||
89             Name.compare(14, 5, "vmlsl", 5) == 0 ||
90             Name.compare(14, 5, "vabdl", 5) == 0 ||
91             Name.compare(14, 5, "vabal", 5) == 0) &&
92            (Name.compare(19, 2, "s.", 2) == 0 ||
93             Name.compare(19, 2, "u.", 2) == 0)) ||
94
95           (Name.compare(14, 4, "vaba", 4) == 0 &&
96            (Name.compare(18, 2, "s.", 2) == 0 ||
97             Name.compare(18, 2, "u.", 2) == 0)) ||
98
99           (Name.compare(14, 6, "vmovn.", 6) == 0)) {
100
101         // Calls to these are transformed into IR without intrinsics.
102         NewFn = 0;
103         return true;
104       }
105       // Old versions of NEON ld/st intrinsics are missing alignment arguments.
106       bool isVLd = (Name.compare(14, 3, "vld", 3) == 0);
107       bool isVSt = (Name.compare(14, 3, "vst", 3) == 0);
108       if (isVLd || isVSt) {
109         unsigned NumVecs = Name.at(17) - '0';
110         if (NumVecs == 0 || NumVecs > 4)
111           return false;
112         bool isLaneOp = (Name.compare(18, 5, "lane.", 5) == 0);
113         if (!isLaneOp && Name.at(18) != '.')
114           return false;
115         unsigned ExpectedArgs = 2; // for the address and alignment
116         if (isVSt || isLaneOp)
117           ExpectedArgs += NumVecs;
118         if (isLaneOp)
119           ExpectedArgs += 1; // for the lane number
120         unsigned NumP = FTy->getNumParams();
121         if (NumP != ExpectedArgs - 1)
122           return false;
123
124         // Change the name of the old (bad) intrinsic, because 
125         // its type is incorrect, but we cannot overload that name.
126         F->setName("");
127
128         // One argument is missing: add the alignment argument.
129         std::vector<const Type*> NewParams;
130         for (unsigned p = 0; p < NumP; ++p)
131           NewParams.push_back(FTy->getParamType(p));
132         NewParams.push_back(Type::getInt32Ty(F->getContext()));
133         FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(),
134                                                  NewParams, false);
135         NewFn = cast<Function>(M->getOrInsertFunction(Name, NewFTy));
136         return true;
137       }
138     }
139     break;
140   case 'b':
141     //  This upgrades the name of the llvm.bswap intrinsic function to only use 
142     //  a single type name for overloading. We only care about the old format
143     //  'llvm.bswap.i*.i*', so check for 'bswap.' and then for there being 
144     //  a '.' after 'bswap.'
145     if (Name.compare(5,6,"bswap.",6) == 0) {
146       std::string::size_type delim = Name.find('.',11);
147       
148       if (delim != std::string::npos) {
149         //  Construct the new name as 'llvm.bswap' + '.i*'
150         F->setName(Name.substr(0,10)+Name.substr(delim));
151         NewFn = F;
152         return true;
153       }
154     }
155     break;
156
157   case 'c':
158     //  We only want to fix the 'llvm.ct*' intrinsics which do not have the 
159     //  correct return type, so we check for the name, and then check if the 
160     //  return type does not match the parameter type.
161     if ( (Name.compare(5,5,"ctpop",5) == 0 ||
162           Name.compare(5,4,"ctlz",4) == 0 ||
163           Name.compare(5,4,"cttz",4) == 0) &&
164         FTy->getReturnType() != FTy->getParamType(0)) {
165       //  We first need to change the name of the old (bad) intrinsic, because 
166       //  its type is incorrect, but we cannot overload that name. We 
167       //  arbitrarily unique it here allowing us to construct a correctly named 
168       //  and typed function below.
169       F->setName("");
170
171       //  Now construct the new intrinsic with the correct name and type. We 
172       //  leave the old function around in order to query its type, whatever it 
173       //  may be, and correctly convert up to the new type.
174       NewFn = cast<Function>(M->getOrInsertFunction(Name, 
175                                                     FTy->getParamType(0),
176                                                     FTy->getParamType(0),
177                                                     (Type *)0));
178       return true;
179     }
180     break;
181
182   case 'e':
183     //  The old llvm.eh.selector.i32 is equivalent to the new llvm.eh.selector.
184     if (Name.compare("llvm.eh.selector.i32") == 0) {
185       F->setName("llvm.eh.selector");
186       NewFn = F;
187       return true;
188     }
189     //  The old llvm.eh.typeid.for.i32 is equivalent to llvm.eh.typeid.for.
190     if (Name.compare("llvm.eh.typeid.for.i32") == 0) {
191       F->setName("llvm.eh.typeid.for");
192       NewFn = F;
193       return true;
194     }
195     //  Convert the old llvm.eh.selector.i64 to a call to llvm.eh.selector.
196     if (Name.compare("llvm.eh.selector.i64") == 0) {
197       NewFn = Intrinsic::getDeclaration(M, Intrinsic::eh_selector);
198       return true;
199     }
200     //  Convert the old llvm.eh.typeid.for.i64 to a call to llvm.eh.typeid.for.
201     if (Name.compare("llvm.eh.typeid.for.i64") == 0) {
202       NewFn = Intrinsic::getDeclaration(M, Intrinsic::eh_typeid_for);
203       return true;
204     }
205     break;
206
207   case 'm': {
208     // This upgrades the llvm.memcpy, llvm.memmove, and llvm.memset to the
209     // new format that allows overloading the pointer for different address
210     // space (e.g., llvm.memcpy.i16 => llvm.memcpy.p0i8.p0i8.i16)
211     const char* NewFnName = NULL;
212     if (Name.compare(5,8,"memcpy.i",8) == 0) {
213       if (Name[13] == '8')
214         NewFnName = "llvm.memcpy.p0i8.p0i8.i8";
215       else if (Name.compare(13,2,"16") == 0)
216         NewFnName = "llvm.memcpy.p0i8.p0i8.i16";
217       else if (Name.compare(13,2,"32") == 0)
218         NewFnName = "llvm.memcpy.p0i8.p0i8.i32";
219       else if (Name.compare(13,2,"64") == 0)
220         NewFnName = "llvm.memcpy.p0i8.p0i8.i64";
221     } else if (Name.compare(5,9,"memmove.i",9) == 0) {
222       if (Name[14] == '8')
223         NewFnName = "llvm.memmove.p0i8.p0i8.i8";
224       else if (Name.compare(14,2,"16") == 0)
225         NewFnName = "llvm.memmove.p0i8.p0i8.i16";
226       else if (Name.compare(14,2,"32") == 0)
227         NewFnName = "llvm.memmove.p0i8.p0i8.i32";
228       else if (Name.compare(14,2,"64") == 0)
229         NewFnName = "llvm.memmove.p0i8.p0i8.i64";
230     }
231     else if (Name.compare(5,8,"memset.i",8) == 0) {
232       if (Name[13] == '8')
233         NewFnName = "llvm.memset.p0i8.i8";
234       else if (Name.compare(13,2,"16") == 0)
235         NewFnName = "llvm.memset.p0i8.i16";
236       else if (Name.compare(13,2,"32") == 0)
237         NewFnName = "llvm.memset.p0i8.i32";
238       else if (Name.compare(13,2,"64") == 0)
239         NewFnName = "llvm.memset.p0i8.i64";
240     }
241     if (NewFnName) {
242       NewFn = cast<Function>(M->getOrInsertFunction(NewFnName, 
243                                             FTy->getReturnType(),
244                                             FTy->getParamType(0),
245                                             FTy->getParamType(1),
246                                             FTy->getParamType(2),
247                                             FTy->getParamType(3),
248                                             Type::getInt1Ty(F->getContext()),
249                                             (Type *)0));
250       return true;
251     }
252     break;
253   }
254   case 'p':
255     //  This upgrades the llvm.part.select overloaded intrinsic names to only 
256     //  use one type specifier in the name. We only care about the old format
257     //  'llvm.part.select.i*.i*', and solve as above with bswap.
258     if (Name.compare(5,12,"part.select.",12) == 0) {
259       std::string::size_type delim = Name.find('.',17);
260       
261       if (delim != std::string::npos) {
262         //  Construct a new name as 'llvm.part.select' + '.i*'
263         F->setName(Name.substr(0,16)+Name.substr(delim));
264         NewFn = F;
265         return true;
266       }
267       break;
268     }
269
270     //  This upgrades the llvm.part.set intrinsics similarly as above, however 
271     //  we care about 'llvm.part.set.i*.i*.i*', but only the first two types 
272     //  must match. There is an additional type specifier after these two 
273     //  matching types that we must retain when upgrading.  Thus, we require 
274     //  finding 2 periods, not just one, after the intrinsic name.
275     if (Name.compare(5,9,"part.set.",9) == 0) {
276       std::string::size_type delim = Name.find('.',14);
277
278       if (delim != std::string::npos &&
279           Name.find('.',delim+1) != std::string::npos) {
280         //  Construct a new name as 'llvm.part.select' + '.i*.i*'
281         F->setName(Name.substr(0,13)+Name.substr(delim));
282         NewFn = F;
283         return true;
284       }
285       break;
286     }
287
288     break;
289   case 'x': 
290     // This fixes all MMX shift intrinsic instructions to take a
291     // v1i64 instead of a v2i32 as the second parameter.
292     if (Name.compare(5,10,"x86.mmx.ps",10) == 0 &&
293         (Name.compare(13,4,"psll", 4) == 0 ||
294          Name.compare(13,4,"psra", 4) == 0 ||
295          Name.compare(13,4,"psrl", 4) == 0) && Name[17] != 'i') {
296       
297       const llvm::Type *VT =
298                     VectorType::get(IntegerType::get(FTy->getContext(), 64), 1);
299       
300       // We don't have to do anything if the parameter already has
301       // the correct type.
302       if (FTy->getParamType(1) == VT)
303         break;
304       
305       //  We first need to change the name of the old (bad) intrinsic, because 
306       //  its type is incorrect, but we cannot overload that name. We 
307       //  arbitrarily unique it here allowing us to construct a correctly named 
308       //  and typed function below.
309       F->setName("");
310
311       assert(FTy->getNumParams() == 2 && "MMX shift intrinsics take 2 args!");
312       
313       //  Now construct the new intrinsic with the correct name and type. We 
314       //  leave the old function around in order to query its type, whatever it 
315       //  may be, and correctly convert up to the new type.
316       NewFn = cast<Function>(M->getOrInsertFunction(Name, 
317                                                     FTy->getReturnType(),
318                                                     FTy->getParamType(0),
319                                                     VT,
320                                                     (Type *)0));
321       return true;
322     } else if (Name.compare(5,17,"x86.sse2.loadh.pd",17) == 0 ||
323                Name.compare(5,17,"x86.sse2.loadl.pd",17) == 0 ||
324                Name.compare(5,16,"x86.sse2.movl.dq",16) == 0 ||
325                Name.compare(5,15,"x86.sse2.movs.d",15) == 0 ||
326                Name.compare(5,16,"x86.sse2.shuf.pd",16) == 0 ||
327                Name.compare(5,18,"x86.sse2.unpckh.pd",18) == 0 ||
328                Name.compare(5,18,"x86.sse2.unpckl.pd",18) == 0 ||
329                Name.compare(5,20,"x86.sse2.punpckh.qdq",20) == 0 ||
330                Name.compare(5,20,"x86.sse2.punpckl.qdq",20) == 0) {
331       // Calls to these intrinsics are transformed into ShuffleVector's.
332       NewFn = 0;
333       return true;
334     } else if (Name.compare(5, 16, "x86.sse41.pmulld", 16) == 0) {
335       // Calls to these intrinsics are transformed into vector multiplies.
336       NewFn = 0;
337       return true;
338     } else if (Name.compare(5, 18, "x86.ssse3.palign.r", 18) == 0 ||
339                Name.compare(5, 22, "x86.ssse3.palign.r.128", 22) == 0) {
340       // Calls to these intrinsics are transformed into vector shuffles, shifts,
341       // or 0.
342       NewFn = 0;
343       return true;           
344     }
345
346     break;
347   }
348
349   //  This may not belong here. This function is effectively being overloaded 
350   //  to both detect an intrinsic which needs upgrading, and to provide the 
351   //  upgraded form of the intrinsic. We should perhaps have two separate 
352   //  functions for this.
353   return false;
354 }
355
356 bool llvm::UpgradeIntrinsicFunction(Function *F, Function *&NewFn) {
357   NewFn = 0;
358   bool Upgraded = UpgradeIntrinsicFunction1(F, NewFn);
359
360   // Upgrade intrinsic attributes.  This does not change the function.
361   if (NewFn)
362     F = NewFn;
363   if (unsigned id = F->getIntrinsicID())
364     F->setAttributes(Intrinsic::getAttributes((Intrinsic::ID)id));
365   return Upgraded;
366 }
367
368 bool llvm::UpgradeGlobalVariable(GlobalVariable *GV) {
369   const std::string &Name = GV->getName();
370
371   // We are only upgrading one symbol here. If we upgrade more, we will want to
372   // perform some sort of short-circuiting like in the
373   // "UpgradeIntrinsicFunction1" function.
374   if (Name == ".llvm.eh.catch.all.value") {
375     GV->setName("llvm.eh.catch.all.value");
376     return true;
377   }
378
379   return false;
380 }
381
382 /// ExtendNEONArgs - For NEON "long" and "wide" operations, where the results
383 /// have vector elements twice as big as one or both source operands, do the
384 /// sign- or zero-extension that used to be handled by intrinsics.  The
385 /// extended values are returned via V0 and V1.
386 static void ExtendNEONArgs(CallInst *CI, Value *Arg0, Value *Arg1,
387                            Value *&V0, Value *&V1) {
388   Function *F = CI->getCalledFunction();
389   const std::string& Name = F->getName();
390   bool isLong = (Name.at(18) == 'l');
391   bool isSigned = (Name.at(19) == 's');
392
393   if (isSigned) {
394     if (isLong)
395       V0 = new SExtInst(Arg0, CI->getType(), "", CI);
396     else
397       V0 = Arg0;
398     V1 = new SExtInst(Arg1, CI->getType(), "", CI);
399   } else {
400     if (isLong)
401       V0 = new ZExtInst(Arg0, CI->getType(), "", CI);
402     else
403       V0 = Arg0;
404     V1 = new ZExtInst(Arg1, CI->getType(), "", CI);
405   }
406 }
407
408 /// CallVABD - As part of expanding a call to one of the old NEON vabdl, vaba,
409 /// or vabal intrinsics, construct a call to a vabd intrinsic.  Examine the
410 /// name of the old intrinsic to determine whether to use a signed or unsigned
411 /// vabd intrinsic.  Get the type from the old call instruction, adjusted for
412 /// half-size vector elements if the old intrinsic was vabdl or vabal.
413 static Instruction *CallVABD(CallInst *CI, Value *Arg0, Value *Arg1) {
414   Function *F = CI->getCalledFunction();
415   const std::string& Name = F->getName();
416   bool isLong = (Name.at(18) == 'l');
417   bool isSigned = (Name.at(isLong ? 19 : 18) == 's');
418
419   Intrinsic::ID intID;
420   if (isSigned)
421     intID = Intrinsic::arm_neon_vabds;
422   else
423     intID = Intrinsic::arm_neon_vabdu;
424
425   const Type *Ty = CI->getType();
426   if (isLong)
427     Ty = VectorType::getTruncatedElementVectorType(cast<const VectorType>(Ty));
428
429   Function *VABD = Intrinsic::getDeclaration(F->getParent(), intID, &Ty, 1);
430   Value *Operands[2];
431   Operands[0] = Arg0;
432   Operands[1] = Arg1;
433   return CallInst::Create(VABD, Operands, Operands+2, 
434                           "upgraded."+CI->getName(), CI);
435 }
436
437 // UpgradeIntrinsicCall - Upgrade a call to an old intrinsic to be a call the 
438 // upgraded intrinsic. All argument and return casting must be provided in 
439 // order to seamlessly integrate with existing context.
440 void llvm::UpgradeIntrinsicCall(CallInst *CI, Function *NewFn) {
441   Function *F = CI->getCalledFunction();
442   LLVMContext &C = CI->getContext();
443   ImmutableCallSite CS(CI);
444
445   assert(F && "CallInst has no function associated with it.");
446
447   if (!NewFn) {
448     // Get the Function's name.
449     const std::string& Name = F->getName();
450
451     // Upgrade ARM NEON intrinsics.
452     if (Name.compare(5, 9, "arm.neon.", 9) == 0) {
453       Instruction *NewI;
454       Value *V0, *V1;
455       if (Name.compare(14, 7, "vmovls.", 7) == 0) {
456         NewI = new SExtInst(CI->getArgOperand(0), CI->getType(),
457                             "upgraded." + CI->getName(), CI);
458       } else if (Name.compare(14, 7, "vmovlu.", 7) == 0) {
459         NewI = new ZExtInst(CI->getArgOperand(0), CI->getType(),
460                             "upgraded." + CI->getName(), CI);
461       } else if (Name.compare(14, 4, "vadd", 4) == 0) {
462         ExtendNEONArgs(CI, CI->getArgOperand(0), CI->getArgOperand(1), V0, V1);
463         NewI = BinaryOperator::CreateAdd(V0, V1, "upgraded."+CI->getName(), CI);
464       } else if (Name.compare(14, 4, "vsub", 4) == 0) {
465         ExtendNEONArgs(CI, CI->getArgOperand(0), CI->getArgOperand(1), V0, V1);
466         NewI = BinaryOperator::CreateSub(V0, V1,"upgraded."+CI->getName(),CI);
467       } else if (Name.compare(14, 4, "vmul", 4) == 0) {
468         ExtendNEONArgs(CI, CI->getArgOperand(0), CI->getArgOperand(1), V0, V1);
469         NewI = BinaryOperator::CreateMul(V0, V1,"upgraded."+CI->getName(),CI);
470       } else if (Name.compare(14, 4, "vmla", 4) == 0) {
471         ExtendNEONArgs(CI, CI->getArgOperand(1), CI->getArgOperand(2), V0, V1);
472         Instruction *MulI = BinaryOperator::CreateMul(V0, V1, "", CI);
473         NewI = BinaryOperator::CreateAdd(CI->getArgOperand(0), MulI,
474                                          "upgraded."+CI->getName(), CI);
475       } else if (Name.compare(14, 4, "vmls", 4) == 0) {
476         ExtendNEONArgs(CI, CI->getArgOperand(1), CI->getArgOperand(2), V0, V1);
477         Instruction *MulI = BinaryOperator::CreateMul(V0, V1, "", CI);
478         NewI = BinaryOperator::CreateSub(CI->getArgOperand(0), MulI,
479                                          "upgraded."+CI->getName(), CI);
480       } else if (Name.compare(14, 4, "vabd", 4) == 0) {
481         NewI = CallVABD(CI, CI->getArgOperand(0), CI->getArgOperand(1));
482         NewI = new ZExtInst(NewI, CI->getType(), "upgraded."+CI->getName(), CI);
483       } else if (Name.compare(14, 4, "vaba", 4) == 0) {
484         NewI = CallVABD(CI, CI->getArgOperand(1), CI->getArgOperand(2));
485         if (Name.at(18) == 'l')
486           NewI = new ZExtInst(NewI, CI->getType(), "", CI);
487         NewI = BinaryOperator::CreateAdd(CI->getArgOperand(0), NewI,
488                                          "upgraded."+CI->getName(), CI);
489       } else if (Name.compare(14, 6, "vmovn.", 6) == 0) {
490         NewI = new TruncInst(CI->getArgOperand(0), CI->getType(),
491                              "upgraded." + CI->getName(), CI);
492       } else {
493         llvm_unreachable("Unknown arm.neon function for CallInst upgrade.");
494       }
495       // Replace any uses of the old CallInst.
496       if (!CI->use_empty())
497         CI->replaceAllUsesWith(NewI);
498       CI->eraseFromParent();
499       return;
500     }
501
502     bool isLoadH = false, isLoadL = false, isMovL = false;
503     bool isMovSD = false, isShufPD = false;
504     bool isUnpckhPD = false, isUnpcklPD = false;
505     bool isPunpckhQPD = false, isPunpcklQPD = false;
506     if (F->getName() == "llvm.x86.sse2.loadh.pd")
507       isLoadH = true;
508     else if (F->getName() == "llvm.x86.sse2.loadl.pd")
509       isLoadL = true;
510     else if (F->getName() == "llvm.x86.sse2.movl.dq")
511       isMovL = true;
512     else if (F->getName() == "llvm.x86.sse2.movs.d")
513       isMovSD = true;
514     else if (F->getName() == "llvm.x86.sse2.shuf.pd")
515       isShufPD = true;
516     else if (F->getName() == "llvm.x86.sse2.unpckh.pd")
517       isUnpckhPD = true;
518     else if (F->getName() == "llvm.x86.sse2.unpckl.pd")
519       isUnpcklPD = true;
520     else if (F->getName() ==  "llvm.x86.sse2.punpckh.qdq")
521       isPunpckhQPD = true;
522     else if (F->getName() ==  "llvm.x86.sse2.punpckl.qdq")
523       isPunpcklQPD = true;
524
525     if (isLoadH || isLoadL || isMovL || isMovSD || isShufPD ||
526         isUnpckhPD || isUnpcklPD || isPunpckhQPD || isPunpcklQPD) {
527       std::vector<Constant*> Idxs;
528       Value *Op0 = CI->getArgOperand(0);
529       ShuffleVectorInst *SI = NULL;
530       if (isLoadH || isLoadL) {
531         Value *Op1 = UndefValue::get(Op0->getType());
532         Value *Addr = new BitCastInst(CI->getArgOperand(1), 
533                                   Type::getDoublePtrTy(C),
534                                       "upgraded.", CI);
535         Value *Load = new LoadInst(Addr, "upgraded.", false, 8, CI);
536         Value *Idx = ConstantInt::get(Type::getInt32Ty(C), 0);
537         Op1 = InsertElementInst::Create(Op1, Load, Idx, "upgraded.", CI);
538
539         if (isLoadH) {
540           Idxs.push_back(ConstantInt::get(Type::getInt32Ty(C), 0));
541           Idxs.push_back(ConstantInt::get(Type::getInt32Ty(C), 2));
542         } else {
543           Idxs.push_back(ConstantInt::get(Type::getInt32Ty(C), 2));
544           Idxs.push_back(ConstantInt::get(Type::getInt32Ty(C), 1));
545         }
546         Value *Mask = ConstantVector::get(Idxs);
547         SI = new ShuffleVectorInst(Op0, Op1, Mask, "upgraded.", CI);
548       } else if (isMovL) {
549         Constant *Zero = ConstantInt::get(Type::getInt32Ty(C), 0);
550         Idxs.push_back(Zero);
551         Idxs.push_back(Zero);
552         Idxs.push_back(Zero);
553         Idxs.push_back(Zero);
554         Value *ZeroV = ConstantVector::get(Idxs);
555
556         Idxs.clear(); 
557         Idxs.push_back(ConstantInt::get(Type::getInt32Ty(C), 4));
558         Idxs.push_back(ConstantInt::get(Type::getInt32Ty(C), 5));
559         Idxs.push_back(ConstantInt::get(Type::getInt32Ty(C), 2));
560         Idxs.push_back(ConstantInt::get(Type::getInt32Ty(C), 3));
561         Value *Mask = ConstantVector::get(Idxs);
562         SI = new ShuffleVectorInst(ZeroV, Op0, Mask, "upgraded.", CI);
563       } else if (isMovSD ||
564                  isUnpckhPD || isUnpcklPD || isPunpckhQPD || isPunpcklQPD) {
565         Value *Op1 = CI->getArgOperand(1);
566         if (isMovSD) {
567           Idxs.push_back(ConstantInt::get(Type::getInt32Ty(C), 2));
568           Idxs.push_back(ConstantInt::get(Type::getInt32Ty(C), 1));
569         } else if (isUnpckhPD || isPunpckhQPD) {
570           Idxs.push_back(ConstantInt::get(Type::getInt32Ty(C), 1));
571           Idxs.push_back(ConstantInt::get(Type::getInt32Ty(C), 3));
572         } else {
573           Idxs.push_back(ConstantInt::get(Type::getInt32Ty(C), 0));
574           Idxs.push_back(ConstantInt::get(Type::getInt32Ty(C), 2));
575         }
576         Value *Mask = ConstantVector::get(Idxs);
577         SI = new ShuffleVectorInst(Op0, Op1, Mask, "upgraded.", CI);
578       } else if (isShufPD) {
579         Value *Op1 = CI->getArgOperand(1);
580         unsigned MaskVal =
581                         cast<ConstantInt>(CI->getArgOperand(2))->getZExtValue();
582         Idxs.push_back(ConstantInt::get(Type::getInt32Ty(C), MaskVal & 1));
583         Idxs.push_back(ConstantInt::get(Type::getInt32Ty(C),
584                                                ((MaskVal >> 1) & 1)+2));
585         Value *Mask = ConstantVector::get(Idxs);
586         SI = new ShuffleVectorInst(Op0, Op1, Mask, "upgraded.", CI);
587       }
588
589       assert(SI && "Unexpected!");
590
591       // Handle any uses of the old CallInst.
592       if (!CI->use_empty())
593         //  Replace all uses of the old call with the new cast which has the 
594         //  correct type.
595         CI->replaceAllUsesWith(SI);
596       
597       //  Clean up the old call now that it has been completely upgraded.
598       CI->eraseFromParent();
599     } else if (F->getName() == "llvm.x86.sse41.pmulld") {
600       // Upgrade this set of intrinsics into vector multiplies.
601       Instruction *Mul = BinaryOperator::CreateMul(CI->getArgOperand(0),
602                                                    CI->getArgOperand(1),
603                                                    CI->getName(),
604                                                    CI);
605       // Fix up all the uses with our new multiply.
606       if (!CI->use_empty())
607         CI->replaceAllUsesWith(Mul);
608         
609       // Remove upgraded multiply.
610       CI->eraseFromParent();
611     } else if (F->getName() == "llvm.x86.ssse3.palign.r") {
612       Value *Op1 = CI->getArgOperand(0);
613       Value *Op2 = CI->getArgOperand(1);
614       Value *Op3 = CI->getArgOperand(2);
615       unsigned shiftVal = cast<ConstantInt>(Op3)->getZExtValue();
616       Value *Rep;
617       IRBuilder<> Builder(C);
618       Builder.SetInsertPoint(CI->getParent(), CI);
619
620       // If palignr is shifting the pair of input vectors less than 9 bytes,
621       // emit a shuffle instruction.
622       if (shiftVal <= 8) {
623         const Type *IntTy = Type::getInt32Ty(C);
624         const Type *EltTy = Type::getInt8Ty(C);
625         const Type *VecTy = VectorType::get(EltTy, 8);
626         
627         Op2 = Builder.CreateBitCast(Op2, VecTy);
628         Op1 = Builder.CreateBitCast(Op1, VecTy);
629
630         llvm::SmallVector<llvm::Constant*, 8> Indices;
631         for (unsigned i = 0; i != 8; ++i)
632           Indices.push_back(ConstantInt::get(IntTy, shiftVal + i));
633
634         Value *SV = ConstantVector::get(Indices.begin(), Indices.size());
635         Rep = Builder.CreateShuffleVector(Op2, Op1, SV, "palignr");
636         Rep = Builder.CreateBitCast(Rep, F->getReturnType());
637       }
638
639       // If palignr is shifting the pair of input vectors more than 8 but less
640       // than 16 bytes, emit a logical right shift of the destination.
641       else if (shiftVal < 16) {
642         // MMX has these as 1 x i64 vectors for some odd optimization reasons.
643         const Type *EltTy = Type::getInt64Ty(C);
644         const Type *VecTy = VectorType::get(EltTy, 1);
645
646         Op1 = Builder.CreateBitCast(Op1, VecTy, "cast");
647         Op2 = ConstantInt::get(VecTy, (shiftVal-8) * 8);
648
649         // create i32 constant
650         Function *I =
651           Intrinsic::getDeclaration(F->getParent(), Intrinsic::x86_mmx_psrl_q);
652         Rep = Builder.CreateCall2(I, Op1, Op2, "palignr");
653       }
654
655       // If palignr is shifting the pair of vectors more than 32 bytes, emit zero.
656       else {
657         Rep = Constant::getNullValue(F->getReturnType());
658       }
659       
660       // Replace any uses with our new instruction.
661       if (!CI->use_empty())
662         CI->replaceAllUsesWith(Rep);
663         
664       // Remove upgraded instruction.
665       CI->eraseFromParent();
666       
667     } else if (F->getName() == "llvm.x86.ssse3.palign.r.128") {
668       Value *Op1 = CI->getArgOperand(0);
669       Value *Op2 = CI->getArgOperand(1);
670       Value *Op3 = CI->getArgOperand(2);
671       unsigned shiftVal = cast<ConstantInt>(Op3)->getZExtValue();
672       Value *Rep;
673       IRBuilder<> Builder(C);
674       Builder.SetInsertPoint(CI->getParent(), CI);
675
676       // If palignr is shifting the pair of input vectors less than 17 bytes,
677       // emit a shuffle instruction.
678       if (shiftVal <= 16) {
679         const Type *IntTy = Type::getInt32Ty(C);
680         const Type *EltTy = Type::getInt8Ty(C);
681         const Type *VecTy = VectorType::get(EltTy, 16);
682         
683         Op2 = Builder.CreateBitCast(Op2, VecTy);
684         Op1 = Builder.CreateBitCast(Op1, VecTy);
685
686         llvm::SmallVector<llvm::Constant*, 16> Indices;
687         for (unsigned i = 0; i != 16; ++i)
688           Indices.push_back(ConstantInt::get(IntTy, shiftVal + i));
689
690         Value *SV = ConstantVector::get(Indices.begin(), Indices.size());
691         Rep = Builder.CreateShuffleVector(Op2, Op1, SV, "palignr");
692         Rep = Builder.CreateBitCast(Rep, F->getReturnType());
693       }
694
695       // If palignr is shifting the pair of input vectors more than 16 but less
696       // than 32 bytes, emit a logical right shift of the destination.
697       else if (shiftVal < 32) {
698         const Type *EltTy = Type::getInt64Ty(C);
699         const Type *VecTy = VectorType::get(EltTy, 2);
700         const Type *IntTy = Type::getInt32Ty(C);
701
702         Op1 = Builder.CreateBitCast(Op1, VecTy, "cast");
703         Op2 = ConstantInt::get(IntTy, (shiftVal-16) * 8);
704
705         // create i32 constant
706         Function *I =
707           Intrinsic::getDeclaration(F->getParent(), Intrinsic::x86_sse2_psrl_dq);
708         Rep = Builder.CreateCall2(I, Op1, Op2, "palignr");
709       }
710
711       // If palignr is shifting the pair of vectors more than 32 bytes, emit zero.
712       else {
713         Rep = Constant::getNullValue(F->getReturnType());
714       }
715       
716       // Replace any uses with our new instruction.
717       if (!CI->use_empty())
718         CI->replaceAllUsesWith(Rep);
719         
720       // Remove upgraded instruction.
721       CI->eraseFromParent();
722       
723     } else {
724       llvm_unreachable("Unknown function for CallInst upgrade.");
725     }
726     return;
727   }
728
729   switch (NewFn->getIntrinsicID()) {
730   default: llvm_unreachable("Unknown function for CallInst upgrade.");
731   case Intrinsic::arm_neon_vld1:
732   case Intrinsic::arm_neon_vld2:
733   case Intrinsic::arm_neon_vld3:
734   case Intrinsic::arm_neon_vld4:
735   case Intrinsic::arm_neon_vst1:
736   case Intrinsic::arm_neon_vst2:
737   case Intrinsic::arm_neon_vst3:
738   case Intrinsic::arm_neon_vst4:
739   case Intrinsic::arm_neon_vld2lane:
740   case Intrinsic::arm_neon_vld3lane:
741   case Intrinsic::arm_neon_vld4lane:
742   case Intrinsic::arm_neon_vst2lane:
743   case Intrinsic::arm_neon_vst3lane:
744   case Intrinsic::arm_neon_vst4lane: {
745     // Add a default alignment argument of 1.
746     SmallVector<Value*, 8> Operands(CS.arg_begin(), CS.arg_end());
747     Operands.push_back(ConstantInt::get(Type::getInt32Ty(C), 1));
748     CallInst *NewCI = CallInst::Create(NewFn, Operands.begin(), Operands.end(),
749                                        CI->getName(), CI);
750     NewCI->setTailCall(CI->isTailCall());
751     NewCI->setCallingConv(CI->getCallingConv());
752
753     //  Handle any uses of the old CallInst.
754     if (!CI->use_empty())
755       //  Replace all uses of the old call with the new cast which has the 
756       //  correct type.
757       CI->replaceAllUsesWith(NewCI);
758     
759     //  Clean up the old call now that it has been completely upgraded.
760     CI->eraseFromParent();
761     break;
762   }        
763
764   case Intrinsic::x86_mmx_psll_d:
765   case Intrinsic::x86_mmx_psll_q:
766   case Intrinsic::x86_mmx_psll_w:
767   case Intrinsic::x86_mmx_psra_d:
768   case Intrinsic::x86_mmx_psra_w:
769   case Intrinsic::x86_mmx_psrl_d:
770   case Intrinsic::x86_mmx_psrl_q:
771   case Intrinsic::x86_mmx_psrl_w: {
772     Value *Operands[2];
773     
774     Operands[0] = CI->getArgOperand(0);
775     
776     // Cast the second parameter to the correct type.
777     BitCastInst *BC = new BitCastInst(CI->getArgOperand(1), 
778                                       NewFn->getFunctionType()->getParamType(1),
779                                       "upgraded.", CI);
780     Operands[1] = BC;
781     
782     //  Construct a new CallInst
783     CallInst *NewCI = CallInst::Create(NewFn, Operands, Operands+2, 
784                                        "upgraded."+CI->getName(), CI);
785     NewCI->setTailCall(CI->isTailCall());
786     NewCI->setCallingConv(CI->getCallingConv());
787     
788     //  Handle any uses of the old CallInst.
789     if (!CI->use_empty())
790       //  Replace all uses of the old call with the new cast which has the 
791       //  correct type.
792       CI->replaceAllUsesWith(NewCI);
793     
794     //  Clean up the old call now that it has been completely upgraded.
795     CI->eraseFromParent();
796     break;
797   }        
798   case Intrinsic::ctlz:
799   case Intrinsic::ctpop:
800   case Intrinsic::cttz: {
801     //  Build a small vector of the original arguments.
802     SmallVector<Value*, 8> Operands(CS.arg_begin(), CS.arg_end());
803
804     //  Construct a new CallInst
805     CallInst *NewCI = CallInst::Create(NewFn, Operands.begin(), Operands.end(),
806                                        "upgraded."+CI->getName(), CI);
807     NewCI->setTailCall(CI->isTailCall());
808     NewCI->setCallingConv(CI->getCallingConv());
809
810     //  Handle any uses of the old CallInst.
811     if (!CI->use_empty()) {
812       //  Check for sign extend parameter attributes on the return values.
813       bool SrcSExt = NewFn->getAttributes().paramHasAttr(0, Attribute::SExt);
814       bool DestSExt = F->getAttributes().paramHasAttr(0, Attribute::SExt);
815       
816       //  Construct an appropriate cast from the new return type to the old.
817       CastInst *RetCast = CastInst::Create(
818                             CastInst::getCastOpcode(NewCI, SrcSExt,
819                                                     F->getReturnType(),
820                                                     DestSExt),
821                             NewCI, F->getReturnType(),
822                             NewCI->getName(), CI);
823       NewCI->moveBefore(RetCast);
824
825       //  Replace all uses of the old call with the new cast which has the 
826       //  correct type.
827       CI->replaceAllUsesWith(RetCast);
828     }
829
830     //  Clean up the old call now that it has been completely upgraded.
831     CI->eraseFromParent();
832   }
833   break;
834   case Intrinsic::eh_selector:
835   case Intrinsic::eh_typeid_for: {
836     // Only the return type changed.
837     SmallVector<Value*, 8> Operands(CS.arg_begin(), CS.arg_end());
838     CallInst *NewCI = CallInst::Create(NewFn, Operands.begin(), Operands.end(),
839                                        "upgraded." + CI->getName(), CI);
840     NewCI->setTailCall(CI->isTailCall());
841     NewCI->setCallingConv(CI->getCallingConv());
842
843     //  Handle any uses of the old CallInst.
844     if (!CI->use_empty()) {
845       //  Construct an appropriate cast from the new return type to the old.
846       CastInst *RetCast =
847         CastInst::Create(CastInst::getCastOpcode(NewCI, true,
848                                                  F->getReturnType(), true),
849                          NewCI, F->getReturnType(), NewCI->getName(), CI);
850       CI->replaceAllUsesWith(RetCast);
851     }
852     CI->eraseFromParent();
853   }
854   break;
855   case Intrinsic::memcpy:
856   case Intrinsic::memmove:
857   case Intrinsic::memset: {
858     // Add isVolatile
859     const llvm::Type *I1Ty = llvm::Type::getInt1Ty(CI->getContext());
860     Value *Operands[5] = { CI->getArgOperand(0), CI->getArgOperand(1),
861                            CI->getArgOperand(2), CI->getArgOperand(3),
862                            llvm::ConstantInt::get(I1Ty, 0) };
863     CallInst *NewCI = CallInst::Create(NewFn, Operands, Operands+5,
864                                        CI->getName(), CI);
865     NewCI->setTailCall(CI->isTailCall());
866     NewCI->setCallingConv(CI->getCallingConv());
867     //  Handle any uses of the old CallInst.
868     if (!CI->use_empty())
869       //  Replace all uses of the old call with the new cast which has the 
870       //  correct type.
871       CI->replaceAllUsesWith(NewCI);
872     
873     //  Clean up the old call now that it has been completely upgraded.
874     CI->eraseFromParent();
875     break;
876   }
877   }
878 }
879
880 // This tests each Function to determine if it needs upgrading. When we find 
881 // one we are interested in, we then upgrade all calls to reflect the new 
882 // function.
883 void llvm::UpgradeCallsToIntrinsic(Function* F) {
884   assert(F && "Illegal attempt to upgrade a non-existent intrinsic.");
885
886   // Upgrade the function and check if it is a totaly new function.
887   Function* NewFn;
888   if (UpgradeIntrinsicFunction(F, NewFn)) {
889     if (NewFn != F) {
890       // Replace all uses to the old function with the new one if necessary.
891       for (Value::use_iterator UI = F->use_begin(), UE = F->use_end();
892            UI != UE; ) {
893         if (CallInst* CI = dyn_cast<CallInst>(*UI++))
894           UpgradeIntrinsicCall(CI, NewFn);
895       }
896       // Remove old function, no longer used, from the module.
897       F->eraseFromParent();
898     }
899   }
900 }
901
902 /// This function strips all debug info intrinsics, except for llvm.dbg.declare.
903 /// If an llvm.dbg.declare intrinsic is invalid, then this function simply
904 /// strips that use.
905 void llvm::CheckDebugInfoIntrinsics(Module *M) {
906
907
908   if (Function *FuncStart = M->getFunction("llvm.dbg.func.start")) {
909     while (!FuncStart->use_empty()) {
910       CallInst *CI = cast<CallInst>(FuncStart->use_back());
911       CI->eraseFromParent();
912     }
913     FuncStart->eraseFromParent();
914   }
915   
916   if (Function *StopPoint = M->getFunction("llvm.dbg.stoppoint")) {
917     while (!StopPoint->use_empty()) {
918       CallInst *CI = cast<CallInst>(StopPoint->use_back());
919       CI->eraseFromParent();
920     }
921     StopPoint->eraseFromParent();
922   }
923
924   if (Function *RegionStart = M->getFunction("llvm.dbg.region.start")) {
925     while (!RegionStart->use_empty()) {
926       CallInst *CI = cast<CallInst>(RegionStart->use_back());
927       CI->eraseFromParent();
928     }
929     RegionStart->eraseFromParent();
930   }
931
932   if (Function *RegionEnd = M->getFunction("llvm.dbg.region.end")) {
933     while (!RegionEnd->use_empty()) {
934       CallInst *CI = cast<CallInst>(RegionEnd->use_back());
935       CI->eraseFromParent();
936     }
937     RegionEnd->eraseFromParent();
938   }
939   
940   if (Function *Declare = M->getFunction("llvm.dbg.declare")) {
941     if (!Declare->use_empty()) {
942       DbgDeclareInst *DDI = cast<DbgDeclareInst>(Declare->use_back());
943       if (!isa<MDNode>(DDI->getArgOperand(0)) ||
944           !isa<MDNode>(DDI->getArgOperand(1))) {
945         while (!Declare->use_empty()) {
946           CallInst *CI = cast<CallInst>(Declare->use_back());
947           CI->eraseFromParent();
948         }
949         Declare->eraseFromParent();
950       }
951     }
952   }
953 }