bbb8462652ca38683b60fc5a14f68d691aedef75
[oota-llvm.git] / lib / IR / 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/IR/AutoUpgrade.h"
15 #include "llvm/IR/CFG.h"
16 #include "llvm/IR/CallSite.h"
17 #include "llvm/IR/Constants.h"
18 #include "llvm/IR/DebugInfo.h"
19 #include "llvm/IR/DiagnosticInfo.h"
20 #include "llvm/IR/Function.h"
21 #include "llvm/IR/IRBuilder.h"
22 #include "llvm/IR/Instruction.h"
23 #include "llvm/IR/IntrinsicInst.h"
24 #include "llvm/IR/LLVMContext.h"
25 #include "llvm/IR/Module.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include <cstring>
28 using namespace llvm;
29
30 // Upgrade the declarations of the SSE4.1 functions whose arguments have
31 // changed their type from v4f32 to v2i64.
32 static bool UpgradeSSE41Function(Function* F, Intrinsic::ID IID,
33                                  Function *&NewFn) {
34   // Check whether this is an old version of the function, which received
35   // v4f32 arguments.
36   Type *Arg0Type = F->getFunctionType()->getParamType(0);
37   if (Arg0Type != VectorType::get(Type::getFloatTy(F->getContext()), 4))
38     return false;
39
40   // Yes, it's old, replace it with new version.
41   F->setName(F->getName() + ".old");
42   NewFn = Intrinsic::getDeclaration(F->getParent(), IID);
43   return true;
44 }
45
46 // Upgrade the declarations of intrinsic functions whose 8-bit immediate mask
47 // arguments have changed their type from i32 to i8.
48 static bool UpgradeX86IntrinsicsWith8BitMask(Function *F, Intrinsic::ID IID,
49                                              Function *&NewFn) {
50   // Check that the last argument is an i32.
51   Type *LastArgType = F->getFunctionType()->getParamType(
52      F->getFunctionType()->getNumParams() - 1);
53   if (!LastArgType->isIntegerTy(32))
54     return false;
55
56   // Move this function aside and map down.
57   F->setName(F->getName() + ".old");
58   NewFn = Intrinsic::getDeclaration(F->getParent(), IID);
59   return true;
60 }
61
62 static bool UpgradeIntrinsicFunction1(Function *F, Function *&NewFn) {
63   assert(F && "Illegal to upgrade a non-existent Function.");
64
65   // Quickly eliminate it, if it's not a candidate.
66   StringRef Name = F->getName();
67   if (Name.size() <= 8 || !Name.startswith("llvm."))
68     return false;
69   Name = Name.substr(5); // Strip off "llvm."
70
71   switch (Name[0]) {
72   default: break;
73   case 'a': {
74     if (Name.startswith("arm.neon.vclz")) {
75       Type* args[2] = {
76         F->arg_begin()->getType(),
77         Type::getInt1Ty(F->getContext())
78       };
79       // Can't use Intrinsic::getDeclaration here as it adds a ".i1" to
80       // the end of the name. Change name from llvm.arm.neon.vclz.* to
81       //  llvm.ctlz.*
82       FunctionType* fType = FunctionType::get(F->getReturnType(), args, false);
83       NewFn = Function::Create(fType, F->getLinkage(),
84                                "llvm.ctlz." + Name.substr(14), F->getParent());
85       return true;
86     }
87     if (Name.startswith("arm.neon.vcnt")) {
88       NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::ctpop,
89                                         F->arg_begin()->getType());
90       return true;
91     }
92     break;
93   }
94   case 'c': {
95     if (Name.startswith("ctlz.") && F->arg_size() == 1) {
96       F->setName(Name + ".old");
97       NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::ctlz,
98                                         F->arg_begin()->getType());
99       return true;
100     }
101     if (Name.startswith("cttz.") && F->arg_size() == 1) {
102       F->setName(Name + ".old");
103       NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::cttz,
104                                         F->arg_begin()->getType());
105       return true;
106     }
107     break;
108   }
109   case 'o':
110     // We only need to change the name to match the mangling including the
111     // address space.
112     if (F->arg_size() == 2 && Name.startswith("objectsize.")) {
113       Type *Tys[2] = { F->getReturnType(), F->arg_begin()->getType() };
114       if (F->getName() != Intrinsic::getName(Intrinsic::objectsize, Tys)) {
115         F->setName(Name + ".old");
116         NewFn = Intrinsic::getDeclaration(F->getParent(),
117                                           Intrinsic::objectsize, Tys);
118         return true;
119       }
120     }
121     break;
122
123   case 'x': {
124     if (Name.startswith("x86.sse2.pcmpeq.") ||
125         Name.startswith("x86.sse2.pcmpgt.") ||
126         Name.startswith("x86.avx2.pcmpeq.") ||
127         Name.startswith("x86.avx2.pcmpgt.") ||
128         Name.startswith("x86.avx.vpermil.") ||
129         Name == "x86.avx.movnt.dq.256" ||
130         Name == "x86.avx.movnt.pd.256" ||
131         Name == "x86.avx.movnt.ps.256" ||
132         Name == "x86.sse42.crc32.64.8" ||
133         Name == "x86.avx.vbroadcast.ss" ||
134         Name == "x86.avx.vbroadcast.ss.256" ||
135         Name == "x86.avx.vbroadcast.sd.256" ||
136         (Name.startswith("x86.xop.vpcom") && F->arg_size() == 2)) {
137       NewFn = nullptr;
138       return true;
139     }
140     // SSE4.1 ptest functions may have an old signature.
141     if (Name.startswith("x86.sse41.ptest")) {
142       if (Name == "x86.sse41.ptestc")
143         return UpgradeSSE41Function(F, Intrinsic::x86_sse41_ptestc, NewFn);
144       if (Name == "x86.sse41.ptestz")
145         return UpgradeSSE41Function(F, Intrinsic::x86_sse41_ptestz, NewFn);
146       if (Name == "x86.sse41.ptestnzc")
147         return UpgradeSSE41Function(F, Intrinsic::x86_sse41_ptestnzc, NewFn);
148     }
149     // Several blend and other instructions with maskes used the wrong number of
150     // bits.
151     if (Name == "x86.sse41.pblendw")
152       return UpgradeX86IntrinsicsWith8BitMask(F, Intrinsic::x86_sse41_pblendw,
153                                               NewFn);
154     if (Name == "x86.sse41.blendpd")
155       return UpgradeX86IntrinsicsWith8BitMask(F, Intrinsic::x86_sse41_blendpd,
156                                               NewFn);
157     if (Name == "x86.sse41.blendps")
158       return UpgradeX86IntrinsicsWith8BitMask(F, Intrinsic::x86_sse41_blendps,
159                                               NewFn);
160     if (Name == "x86.sse41.insertps")
161       return UpgradeX86IntrinsicsWith8BitMask(F, Intrinsic::x86_sse41_insertps,
162                                               NewFn);
163     if (Name == "x86.sse41.dppd")
164       return UpgradeX86IntrinsicsWith8BitMask(F, Intrinsic::x86_sse41_dppd,
165                                               NewFn);
166     if (Name == "x86.sse41.dpps")
167       return UpgradeX86IntrinsicsWith8BitMask(F, Intrinsic::x86_sse41_dpps,
168                                               NewFn);
169     if (Name == "x86.sse41.mpsadbw")
170       return UpgradeX86IntrinsicsWith8BitMask(F, Intrinsic::x86_sse41_mpsadbw,
171                                               NewFn);
172     if (Name == "x86.avx.blend.pd.256")
173       return UpgradeX86IntrinsicsWith8BitMask(
174           F, Intrinsic::x86_avx_blend_pd_256, NewFn);
175     if (Name == "x86.avx.blend.ps.256")
176       return UpgradeX86IntrinsicsWith8BitMask(
177           F, Intrinsic::x86_avx_blend_ps_256, NewFn);
178     if (Name == "x86.avx.dp.ps.256")
179       return UpgradeX86IntrinsicsWith8BitMask(F, Intrinsic::x86_avx_dp_ps_256,
180                                               NewFn);
181     if (Name == "x86.avx2.pblendw")
182       return UpgradeX86IntrinsicsWith8BitMask(F, Intrinsic::x86_avx2_pblendw,
183                                               NewFn);
184     if (Name == "x86.avx2.pblendd.128")
185       return UpgradeX86IntrinsicsWith8BitMask(
186           F, Intrinsic::x86_avx2_pblendd_128, NewFn);
187     if (Name == "x86.avx2.pblendd.256")
188       return UpgradeX86IntrinsicsWith8BitMask(
189           F, Intrinsic::x86_avx2_pblendd_256, NewFn);
190     if (Name == "x86.avx2.mpsadbw")
191       return UpgradeX86IntrinsicsWith8BitMask(F, Intrinsic::x86_avx2_mpsadbw,
192                                               NewFn);
193
194     // frcz.ss/sd may need to have an argument dropped
195     if (Name.startswith("x86.xop.vfrcz.ss") && F->arg_size() == 2) {
196       F->setName(Name + ".old");
197       NewFn = Intrinsic::getDeclaration(F->getParent(),
198                                         Intrinsic::x86_xop_vfrcz_ss);
199       return true;
200     }
201     if (Name.startswith("x86.xop.vfrcz.sd") && F->arg_size() == 2) {
202       F->setName(Name + ".old");
203       NewFn = Intrinsic::getDeclaration(F->getParent(),
204                                         Intrinsic::x86_xop_vfrcz_sd);
205       return true;
206     }
207     // Fix the FMA4 intrinsics to remove the 4
208     if (Name.startswith("x86.fma4.")) {
209       F->setName("llvm.x86.fma" + Name.substr(8));
210       NewFn = F;
211       return true;
212     }
213     break;
214   }
215   }
216
217   //  This may not belong here. This function is effectively being overloaded
218   //  to both detect an intrinsic which needs upgrading, and to provide the
219   //  upgraded form of the intrinsic. We should perhaps have two separate
220   //  functions for this.
221   return false;
222 }
223
224 bool llvm::UpgradeIntrinsicFunction(Function *F, Function *&NewFn) {
225   NewFn = nullptr;
226   bool Upgraded = UpgradeIntrinsicFunction1(F, NewFn);
227
228   // Upgrade intrinsic attributes.  This does not change the function.
229   if (NewFn)
230     F = NewFn;
231   if (unsigned id = F->getIntrinsicID())
232     F->setAttributes(Intrinsic::getAttributes(F->getContext(),
233                                               (Intrinsic::ID)id));
234   return Upgraded;
235 }
236
237 bool llvm::UpgradeGlobalVariable(GlobalVariable *GV) {
238   // Nothing to do yet.
239   return false;
240 }
241
242 // UpgradeIntrinsicCall - Upgrade a call to an old intrinsic to be a call the
243 // upgraded intrinsic. All argument and return casting must be provided in
244 // order to seamlessly integrate with existing context.
245 void llvm::UpgradeIntrinsicCall(CallInst *CI, Function *NewFn) {
246   Function *F = CI->getCalledFunction();
247   LLVMContext &C = CI->getContext();
248   IRBuilder<> Builder(C);
249   Builder.SetInsertPoint(CI->getParent(), CI);
250
251   assert(F && "Intrinsic call is not direct?");
252
253   if (!NewFn) {
254     // Get the Function's name.
255     StringRef Name = F->getName();
256
257     Value *Rep;
258     // Upgrade packed integer vector compares intrinsics to compare instructions
259     if (Name.startswith("llvm.x86.sse2.pcmpeq.") ||
260         Name.startswith("llvm.x86.avx2.pcmpeq.")) {
261       Rep = Builder.CreateICmpEQ(CI->getArgOperand(0), CI->getArgOperand(1),
262                                  "pcmpeq");
263       // need to sign extend since icmp returns vector of i1
264       Rep = Builder.CreateSExt(Rep, CI->getType(), "");
265     } else if (Name.startswith("llvm.x86.sse2.pcmpgt.") ||
266                Name.startswith("llvm.x86.avx2.pcmpgt.")) {
267       Rep = Builder.CreateICmpSGT(CI->getArgOperand(0), CI->getArgOperand(1),
268                                   "pcmpgt");
269       // need to sign extend since icmp returns vector of i1
270       Rep = Builder.CreateSExt(Rep, CI->getType(), "");
271     } else if (Name == "llvm.x86.avx.movnt.dq.256" ||
272                Name == "llvm.x86.avx.movnt.ps.256" ||
273                Name == "llvm.x86.avx.movnt.pd.256") {
274       IRBuilder<> Builder(C);
275       Builder.SetInsertPoint(CI->getParent(), CI);
276
277       Module *M = F->getParent();
278       SmallVector<Value *, 1> Elts;
279       Elts.push_back(ConstantInt::get(Type::getInt32Ty(C), 1));
280       MDNode *Node = MDNode::get(C, Elts);
281
282       Value *Arg0 = CI->getArgOperand(0);
283       Value *Arg1 = CI->getArgOperand(1);
284
285       // Convert the type of the pointer to a pointer to the stored type.
286       Value *BC = Builder.CreateBitCast(Arg0,
287                                         PointerType::getUnqual(Arg1->getType()),
288                                         "cast");
289       StoreInst *SI = Builder.CreateStore(Arg1, BC);
290       SI->setMetadata(M->getMDKindID("nontemporal"), Node);
291       SI->setAlignment(16);
292
293       // Remove intrinsic.
294       CI->eraseFromParent();
295       return;
296     } else if (Name.startswith("llvm.x86.xop.vpcom")) {
297       Intrinsic::ID intID;
298       if (Name.endswith("ub"))
299         intID = Intrinsic::x86_xop_vpcomub;
300       else if (Name.endswith("uw"))
301         intID = Intrinsic::x86_xop_vpcomuw;
302       else if (Name.endswith("ud"))
303         intID = Intrinsic::x86_xop_vpcomud;
304       else if (Name.endswith("uq"))
305         intID = Intrinsic::x86_xop_vpcomuq;
306       else if (Name.endswith("b"))
307         intID = Intrinsic::x86_xop_vpcomb;
308       else if (Name.endswith("w"))
309         intID = Intrinsic::x86_xop_vpcomw;
310       else if (Name.endswith("d"))
311         intID = Intrinsic::x86_xop_vpcomd;
312       else if (Name.endswith("q"))
313         intID = Intrinsic::x86_xop_vpcomq;
314       else
315         llvm_unreachable("Unknown suffix");
316
317       Name = Name.substr(18); // strip off "llvm.x86.xop.vpcom"
318       unsigned Imm;
319       if (Name.startswith("lt"))
320         Imm = 0;
321       else if (Name.startswith("le"))
322         Imm = 1;
323       else if (Name.startswith("gt"))
324         Imm = 2;
325       else if (Name.startswith("ge"))
326         Imm = 3;
327       else if (Name.startswith("eq"))
328         Imm = 4;
329       else if (Name.startswith("ne"))
330         Imm = 5;
331       else if (Name.startswith("true"))
332         Imm = 6;
333       else if (Name.startswith("false"))
334         Imm = 7;
335       else
336         llvm_unreachable("Unknown condition");
337
338       Function *VPCOM = Intrinsic::getDeclaration(F->getParent(), intID);
339       Rep = Builder.CreateCall3(VPCOM, CI->getArgOperand(0),
340                                 CI->getArgOperand(1), Builder.getInt8(Imm));
341     } else if (Name == "llvm.x86.sse42.crc32.64.8") {
342       Function *CRC32 = Intrinsic::getDeclaration(F->getParent(),
343                                                Intrinsic::x86_sse42_crc32_32_8);
344       Value *Trunc0 = Builder.CreateTrunc(CI->getArgOperand(0), Type::getInt32Ty(C));
345       Rep = Builder.CreateCall2(CRC32, Trunc0, CI->getArgOperand(1));
346       Rep = Builder.CreateZExt(Rep, CI->getType(), "");
347     } else if (Name.startswith("llvm.x86.avx.vbroadcast")) {
348       // Replace broadcasts with a series of insertelements.
349       Type *VecTy = CI->getType();
350       Type *EltTy = VecTy->getVectorElementType();
351       unsigned EltNum = VecTy->getVectorNumElements();
352       Value *Cast = Builder.CreateBitCast(CI->getArgOperand(0),
353                                           EltTy->getPointerTo());
354       Value *Load = Builder.CreateLoad(Cast);
355       Type *I32Ty = Type::getInt32Ty(C);
356       Rep = UndefValue::get(VecTy);
357       for (unsigned I = 0; I < EltNum; ++I)
358         Rep = Builder.CreateInsertElement(Rep, Load,
359                                           ConstantInt::get(I32Ty, I));
360     } else {
361       bool PD128 = false, PD256 = false, PS128 = false, PS256 = false;
362       if (Name == "llvm.x86.avx.vpermil.pd.256")
363         PD256 = true;
364       else if (Name == "llvm.x86.avx.vpermil.pd")
365         PD128 = true;
366       else if (Name == "llvm.x86.avx.vpermil.ps.256")
367         PS256 = true;
368       else if (Name == "llvm.x86.avx.vpermil.ps")
369         PS128 = true;
370
371       if (PD256 || PD128 || PS256 || PS128) {
372         Value *Op0 = CI->getArgOperand(0);
373         unsigned Imm = cast<ConstantInt>(CI->getArgOperand(1))->getZExtValue();
374         SmallVector<Constant*, 8> Idxs;
375
376         if (PD128)
377           for (unsigned i = 0; i != 2; ++i)
378             Idxs.push_back(Builder.getInt32((Imm >> i) & 0x1));
379         else if (PD256)
380           for (unsigned l = 0; l != 4; l+=2)
381             for (unsigned i = 0; i != 2; ++i)
382               Idxs.push_back(Builder.getInt32(((Imm >> (l+i)) & 0x1) + l));
383         else if (PS128)
384           for (unsigned i = 0; i != 4; ++i)
385             Idxs.push_back(Builder.getInt32((Imm >> (2 * i)) & 0x3));
386         else if (PS256)
387           for (unsigned l = 0; l != 8; l+=4)
388             for (unsigned i = 0; i != 4; ++i)
389               Idxs.push_back(Builder.getInt32(((Imm >> (2 * i)) & 0x3) + l));
390         else
391           llvm_unreachable("Unexpected function");
392
393         Rep = Builder.CreateShuffleVector(Op0, Op0, ConstantVector::get(Idxs));
394       } else {
395         llvm_unreachable("Unknown function for CallInst upgrade.");
396       }
397     }
398
399     CI->replaceAllUsesWith(Rep);
400     CI->eraseFromParent();
401     return;
402   }
403
404   std::string Name = CI->getName().str();
405   CI->setName(Name + ".old");
406
407   switch (NewFn->getIntrinsicID()) {
408   default:
409     llvm_unreachable("Unknown function for CallInst upgrade.");
410
411   case Intrinsic::ctlz:
412   case Intrinsic::cttz:
413     assert(CI->getNumArgOperands() == 1 &&
414            "Mismatch between function args and call args");
415     CI->replaceAllUsesWith(Builder.CreateCall2(NewFn, CI->getArgOperand(0),
416                                                Builder.getFalse(), Name));
417     CI->eraseFromParent();
418     return;
419
420   case Intrinsic::objectsize:
421     CI->replaceAllUsesWith(Builder.CreateCall2(NewFn,
422                                                CI->getArgOperand(0),
423                                                CI->getArgOperand(1),
424                                                Name));
425     CI->eraseFromParent();
426     return;
427
428   case Intrinsic::arm_neon_vclz: {
429     // Change name from llvm.arm.neon.vclz.* to llvm.ctlz.*
430     CI->replaceAllUsesWith(Builder.CreateCall2(NewFn, CI->getArgOperand(0),
431                                                Builder.getFalse(),
432                                                "llvm.ctlz." + Name.substr(14)));
433     CI->eraseFromParent();
434     return;
435   }
436   case Intrinsic::ctpop: {
437     CI->replaceAllUsesWith(Builder.CreateCall(NewFn, CI->getArgOperand(0)));
438     CI->eraseFromParent();
439     return;
440   }
441
442   case Intrinsic::x86_xop_vfrcz_ss:
443   case Intrinsic::x86_xop_vfrcz_sd:
444     CI->replaceAllUsesWith(Builder.CreateCall(NewFn, CI->getArgOperand(1),
445                                               Name));
446     CI->eraseFromParent();
447     return;
448
449   case Intrinsic::x86_sse41_ptestc:
450   case Intrinsic::x86_sse41_ptestz:
451   case Intrinsic::x86_sse41_ptestnzc: {
452     // The arguments for these intrinsics used to be v4f32, and changed
453     // to v2i64. This is purely a nop, since those are bitwise intrinsics.
454     // So, the only thing required is a bitcast for both arguments.
455     // First, check the arguments have the old type.
456     Value *Arg0 = CI->getArgOperand(0);
457     if (Arg0->getType() != VectorType::get(Type::getFloatTy(C), 4))
458       return;
459
460     // Old intrinsic, add bitcasts
461     Value *Arg1 = CI->getArgOperand(1);
462
463     Value *BC0 =
464       Builder.CreateBitCast(Arg0,
465                             VectorType::get(Type::getInt64Ty(C), 2),
466                             "cast");
467     Value *BC1 =
468       Builder.CreateBitCast(Arg1,
469                             VectorType::get(Type::getInt64Ty(C), 2),
470                             "cast");
471
472     CallInst* NewCall = Builder.CreateCall2(NewFn, BC0, BC1, Name);
473     CI->replaceAllUsesWith(NewCall);
474     CI->eraseFromParent();
475     return;
476   }
477
478   case Intrinsic::x86_sse41_pblendw:
479   case Intrinsic::x86_sse41_blendpd:
480   case Intrinsic::x86_sse41_blendps:
481   case Intrinsic::x86_sse41_insertps:
482   case Intrinsic::x86_sse41_dppd:
483   case Intrinsic::x86_sse41_dpps:
484   case Intrinsic::x86_sse41_mpsadbw:
485   case Intrinsic::x86_avx_blend_pd_256:
486   case Intrinsic::x86_avx_blend_ps_256:
487   case Intrinsic::x86_avx_dp_ps_256:
488   case Intrinsic::x86_avx2_pblendw:
489   case Intrinsic::x86_avx2_pblendd_128:
490   case Intrinsic::x86_avx2_pblendd_256:
491   case Intrinsic::x86_avx2_mpsadbw: {
492     // Need to truncate the last argument from i32 to i8 -- this argument models
493     // an inherently 8-bit immediate operand to these x86 instructions.
494     SmallVector<Value *, 4> Args(CI->arg_operands().begin(),
495                                  CI->arg_operands().end());
496
497     // Replace the last argument with a trunc.
498     Args.back() = Builder.CreateTrunc(Args.back(), Type::getInt8Ty(C), "trunc");
499
500     CallInst *NewCall = Builder.CreateCall(NewFn, Args);
501     CI->replaceAllUsesWith(NewCall);
502     CI->eraseFromParent();
503     return;
504   }
505   }
506 }
507
508 // This tests each Function to determine if it needs upgrading. When we find
509 // one we are interested in, we then upgrade all calls to reflect the new
510 // function.
511 void llvm::UpgradeCallsToIntrinsic(Function* F) {
512   assert(F && "Illegal attempt to upgrade a non-existent intrinsic.");
513
514   // Upgrade the function and check if it is a totaly new function.
515   Function *NewFn;
516   if (UpgradeIntrinsicFunction(F, NewFn)) {
517     if (NewFn != F) {
518       // Replace all uses to the old function with the new one if necessary.
519       for (Value::user_iterator UI = F->user_begin(), UE = F->user_end();
520            UI != UE; ) {
521         if (CallInst *CI = dyn_cast<CallInst>(*UI++))
522           UpgradeIntrinsicCall(CI, NewFn);
523       }
524       // Remove old function, no longer used, from the module.
525       F->eraseFromParent();
526     }
527   }
528 }
529
530 void llvm::UpgradeInstWithTBAATag(Instruction *I) {
531   MDNode *MD = I->getMetadata(LLVMContext::MD_tbaa);
532   assert(MD && "UpgradeInstWithTBAATag should have a TBAA tag");
533   // Check if the tag uses struct-path aware TBAA format.
534   if (isa<MDNode>(MD->getOperand(0)) && MD->getNumOperands() >= 3)
535     return;
536
537   if (MD->getNumOperands() == 3) {
538     Value *Elts[] = {
539       MD->getOperand(0),
540       MD->getOperand(1)
541     };
542     MDNode *ScalarType = MDNode::get(I->getContext(), Elts);
543     // Create a MDNode <ScalarType, ScalarType, offset 0, const>
544     Value *Elts2[] = {
545       ScalarType, ScalarType,
546       Constant::getNullValue(Type::getInt64Ty(I->getContext())),
547       MD->getOperand(2)
548     };
549     I->setMetadata(LLVMContext::MD_tbaa, MDNode::get(I->getContext(), Elts2));
550   } else {
551     // Create a MDNode <MD, MD, offset 0>
552     Value *Elts[] = {MD, MD,
553       Constant::getNullValue(Type::getInt64Ty(I->getContext()))};
554     I->setMetadata(LLVMContext::MD_tbaa, MDNode::get(I->getContext(), Elts));
555   }
556 }
557
558 Instruction *llvm::UpgradeBitCastInst(unsigned Opc, Value *V, Type *DestTy,
559                                       Instruction *&Temp) {
560   if (Opc != Instruction::BitCast)
561     return nullptr;
562
563   Temp = nullptr;
564   Type *SrcTy = V->getType();
565   if (SrcTy->isPtrOrPtrVectorTy() && DestTy->isPtrOrPtrVectorTy() &&
566       SrcTy->getPointerAddressSpace() != DestTy->getPointerAddressSpace()) {
567     LLVMContext &Context = V->getContext();
568
569     // We have no information about target data layout, so we assume that
570     // the maximum pointer size is 64bit.
571     Type *MidTy = Type::getInt64Ty(Context);
572     Temp = CastInst::Create(Instruction::PtrToInt, V, MidTy);
573
574     return CastInst::Create(Instruction::IntToPtr, Temp, DestTy);
575   }
576
577   return nullptr;
578 }
579
580 Value *llvm::UpgradeBitCastExpr(unsigned Opc, Constant *C, Type *DestTy) {
581   if (Opc != Instruction::BitCast)
582     return nullptr;
583
584   Type *SrcTy = C->getType();
585   if (SrcTy->isPtrOrPtrVectorTy() && DestTy->isPtrOrPtrVectorTy() &&
586       SrcTy->getPointerAddressSpace() != DestTy->getPointerAddressSpace()) {
587     LLVMContext &Context = C->getContext();
588
589     // We have no information about target data layout, so we assume that
590     // the maximum pointer size is 64bit.
591     Type *MidTy = Type::getInt64Ty(Context);
592
593     return ConstantExpr::getIntToPtr(ConstantExpr::getPtrToInt(C, MidTy),
594                                      DestTy);
595   }
596
597   return nullptr;
598 }
599
600 /// Check the debug info version number, if it is out-dated, drop the debug
601 /// info. Return true if module is modified.
602 bool llvm::UpgradeDebugInfo(Module &M) {
603   unsigned Version = getDebugMetadataVersionFromModule(M);
604   if (Version == DEBUG_METADATA_VERSION)
605     return false;
606
607   bool RetCode = StripDebugInfo(M);
608   if (RetCode) {
609     DiagnosticInfoDebugMetadataVersion DiagVersion(M, Version);
610     M.getContext().diagnose(DiagVersion);
611   }
612   return RetCode;
613 }
614
615 void llvm::UpgradeMDStringConstant(std::string &String) {
616   const std::string OldPrefix = "llvm.vectorizer.";
617   if (String == "llvm.vectorizer.unroll") {
618     String = "llvm.loop.interleave.count";
619   } else if (String.find(OldPrefix) == 0) {
620     String.replace(0, OldPrefix.size(), "llvm.loop.vectorize.");
621   }
622 }